最近在优化项目,发现有很多公用的方法和属性,所以计划把这些公用的状态提取出来,所以选择VueX,将公用状态分发给多个组件复用,使得状态管理更为清晰,方便项目的维护。
1、目录结构的设计
- store:目录名称
- index.js:状态管理实例的创建
- state.js:公共管理的状态
- mutation.js:用于状态值的修改
- mutationType.js:mutations的类型设置,使用常量,建议使用大写
- actions.js:用于提交mutations
2、action和mutation的区别
mutation有必须同步执行这个限制;
action不受限制,可以执行异步操作;
3、具体实现
【index.js】
import Vue from 'vue';
import Vuex from 'vuex';
import state from './state';
import actions from './actions';
import mutations from './mutations';
Vue.use(Vuex);
export default new Vuex.Store({
state,
mutations,
actions
})
【state.js】
export default {
company: {}
}
【mutationType.js】
export const GET_COMPANY = 'GET_COMPANY';
【mutation.js】
import * as types from './mutationTypes';
export default {
[types.GET_COMPANY](state, company) {
state.company = company;
}
}
【actions.js】
import * as types from './mutationTypes';
import N from '@/js/libs/network';
export default {
getCompany: function (context, queryId) {
N.jsonGet(
url,
{
id: queryId
},
{
success: data => {
context.commit(types.GET_COMPANY, data);
},
fail: XMLHttpRequest => {
errorHandler(XMLHttpRequest);
}
}
)
}
}
state的更改
this.$store.dispatch('getCompany', {});
大致的用法就是这个样子,希望可以帮助到大家。