目录在Vue项目中使用vuex一、安装vuex二、创建store三、挂载store四、在组件中使用五、在Vue组件中监听Vuex总结在Vue项目中使用vuex 在一个vue项目中使用
在一个vue项目中使用vuex,需要根据项目来源分两种情况 :
具体如下图示:
这里我们主要说明第一种情况,在一个老项目中如何使用vuex,步骤如下:
1.首先安装vuex包,安装完之后开始配置
2.在src目录下创建一个文件夹store,在store文件夹中新建一个index.js文件
3.创建Vuex.store实例 :index.js中进行如下配置:
4.向Vue实例注入store:main.js中进行如下配置:
5.配置完后就可以在任意组件中使用了
在任意组件中,通过this.$store.state 来获取公共数据,在模板中,则可以省略this而直接写成: {{$store.state.属性名}}
npm install vuex --save
在项目src目录下创建store目录,在store目录中创建index.js文件。
写入一下内容:
import Vue from 'vue'
import Vuex from 'vuex'
// 挂在Vuex
Vue.use(Vuex)
// 创建Vuex对象
const store = new Vuex.Store({
state:{
// 存放的键值对就是所要管理的状态
// 以key:value为例
key : value,
},
mutations:{
seTKEy(state, payload) {
state.key = payload;
}
}
})
export default store
在main.js中,添加代码:
import store from './store'
new Vue({
el: '#app',
router,
store: store, //store:store 和 router一样,将我们创建的Vuex实例挂载到这个vue实例中
components: { App },
template: '<App/>'
})
将需要使用的值写在computed中:
computed:{
key() {
return this.$store.state.key;
}
}
如果在组件中使用v-model绑定computed中的值,需要在computed中定义set方法,如下:
computed:{
key:{
get(){
return this.$store.state.key;
},
set(val){
this.$store.commit('setKey', val);
}
}
}
在Vue组件中监听Vuex:
computed:{
key(){
return this.$store.state.key;
}
},
watch:{
key(val) {
// 要做的操作
}
}
以上为个人经验,希望能给大家一个参考,也希望大家多多支持编程网。
--结束END--
本文标题: 如何在Vue项目中使用vuex
本文链接: https://www.lsjlt.com/news/178324.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
下载Word文档到电脑,方便收藏和打印~
2024-01-12
2023-05-20
2023-05-20
2023-05-20
2023-05-20
2023-05-20
2023-05-20
2023-05-20
2023-05-20
2023-05-20
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0