一.安装依赖
npm install vuex>vuex --save
或者
cnpm install vuex>vuex --save
二.引入
为了便于维护。在vue项目中的src目录下新建目录store,
在改store目录下新建index.js文件和一个modules目录
index.js文件如下
import Vue from "vue"
import Vuex from "vuex>vuex"
import account from "./modules/account"
import setting from "./modules/setting"
Vue.use(Vuex)
export default new Vuex.Store({
modules: {
account,
setting
}
})
modules目录下有两个文件分别是account.js和setting.js
在account.js文件下
export default {
namespaced: true,
state: {
user: {}
},
actions: {
setuser (ctx, user) {
ctx.commit("setuser", user);
}
},
mutations: {
setuser(state, user) {
state.user = user;
}
}
}
另一文件一样的格式
最后在main.js文件引入我们写好的src/store/index/js文件
import store from "./store"
new Vue({
el: '#app',
router,
store,
components: { App },
template: '<App/>'
})
ro
三.使用
用了这种分模块的方式写store,在使用store的数据的时候就能写成
this.$store.state.user
这种格式了
我们要写成如下的这种格式
this.$store.account.state.user
就是到仓库中先寻找到account模块,然后再在模块中的state。。
并且在dispatch的时候如下
this.$store.dispatch('account/setuser', user)
不能写成下面的形式
this.$store.dispatch('setuser', user)
都是需要先找到对应的模块才行