一:安装
npm install vuex@next --save
二:使用
第一步:main.js中进行引入
//main.js
import Vue from 'vue'
import App from './App'
import store from './store/index'//第一步
new Vue({
el: '#app',
store,//第二步
components: { App },
template: '<App/>'
});
第二步:写store文件
//store/index.js
import Vue from 'vue'
import Vuex from 'vuex'
import user from './modules/user'
Vue.use(Vuex)
export default new Vuex.Store({
// 模块化开发
modules: {
user
}
})
第三步:写数据文件 user.js
//user.js
const actions = { //actions提交的是mutations,相当于就是改变变量的方法的重写,但是,actions是可以进行异步操作的
setUsername(content) {
content.commit('SET_username');
}
};
const mutations = { //修改store中的变量的方法,如果你要改变变量的值,就写这里
SET_username(state, value) {
state.username = value;
},
};
const state = ({ //state里面存放的是变量,如果你要注册全局变量,写这里
username:'',
});
const getters = { //getters相当于是state的计算属性,如果你需要将变量的值进行计算,然后输出,写这里
fullName(state){
return state.username + '用户';
}};
export default{
namespaced:true,//开启命名空间
state,
getters,
mutations,
actions
};
开启命名空间方法二 (代码与上面内容无关)
// store/modules/myModule.js
const myModule = {
namespaced: true, // 开启命名空间
state: {
// 模块内的状态
count: 0
},
mutations: {
// 模块内的mutations
increment(state) {
state.count++;
}
},
actions: {
// 模块内的actions
incrementAsync({ commit }) {
setTimeout(() => {
commit('increment');
}, 1000);
}
},
getters: {
// 模块内的getters
doubleCount(state) {
return state.count * 2;
}
}
};
export default myModule;