1,vuex是专为vue.js设计的状态管理模式,集中存储和管理应用程序中所有组件的状态,适用于中大型单页应用
2,使用vuex的第一步: 引入
import Vue from 'vue';
import Vuex from 'vuex';
Vue.use(Vuex);
同样需要在main.js中引入store
import store from './store';
window.$vue = new Vue({
router,
store,
render: h => h(App),
}).$mount('#app');
3,接下来就是使用了,如果项目比较小不需要分模块可以像下面这样写,把所有的状态集中在一个文件内
const store = new Vuex.Store({
state,
mutations,
actions,
getters,
strict: process.env.NODE_ENV !== 'production'
});
window.store = store;
export default store;
如果项目比较大,建议分模块处理,如下
import users from './modules/users';
import appManagement from './modules/appManagement';
import account from './modules/account';
const store = new Vuex.Store({
state,
mutations,
actions,
getters,
modules: {
users,
appManagement,
account
},
strict: process.env.NODE_ENV !== 'production'
});
window.store = store;
export default store;
在上面的代码中引入了users/appManagement/ account三个模块在每个模块内的代码如下
这样代码更清晰,便于查找,namespaced相当于命名空间,在引入方法的时候需要加上所属模块的模块名
4,接下来就是在各个模块内的使用了,这里就说最简单的。使用mapGetters,mapActions,mapMutations,mapState
import { mapActions, mapMutations, mapGetters } from 'vuex';
computed: {
...mapGetters('appManagement', [
'tableDatas',
'paginationDatas',
'clientList',
'newClient',
'userInfo',
'isAdd',
'isChangeName'
]),
},
methods: {
...mapActions('appManagement', [
'getApps',
'getClient',
'addUserLists',
'upDateUserLists',
'able',
'unable',
'addNewClient',
'validateName'
]),
...mapMutations('appManagement', [
'updateSearchDatas',
'updatePageData',
'updateNewClient',
'getUserInfo',
'uploadIsAdd',
'uploadIsChangeName'
]),
}
通过map的方式引入方法以及状态是可以直接使用的,就和使用methods内的方法和data内的属性一样的,这里使用mapGetters 的好处是可以对数据进行一步处理,例如过滤筛选,
另外就是有一点需要注意的: 状态改变必须通过mutation显式的提交,例如await一个一步请求完成之后通过commit提交数据
//action
async getClient({ commit }, data) {
const result = await appManagement.getClient(data);
commit('uploadClientList', result.data.data);
},
//mutation
uploadClientList(state, data) {
state.clientList = data;
},
如有错误,敬请指出