vuex-actions
- 在使用vuex时,有时需要使用异步操作,但是在mutations中是不支持异步操作的,这是就需要使用actions属性了
- actions属性的使用方法与mutations类似,都是形式为函数形式,不同的是actions属性的默认参数为context,还可以添加其他的参数,使用payload来表示,类型为对象类型
actions: {
actUpdateInfo(context, payload) {
setTimeout(() => {
context.commit('updateInfo');
}, 1000);
console.log(payload);
}
}
- 需要注意的是,对actions进行操作时,为了能够实现vuex对数据的追踪,必须在actions中使用mutations来对数据进行修改
- 在组件中调用该actions属性时使用dispatch()函数。
this.$store.dispatch('actUpdateInfo', '显示内容:');
- 为了实现对state进行修改后的提示操作,使用Promise来进行信息的打印。对actions进行修改,返回值为Promise对象
actUpdateInfo(context, payload) {
return new Promise((resolve, reject) => {
setTimeout(() => {
context.commit('updateInfo');
}, 1000);
console.log(payload);
resolve('使用Promise进行actions操作');
});
}
- 在组件中对actions函数进行操作,由于返回值为Promise对象,使用then方法进行相应的操作,打印相关信息
update() {
this.$store.dispatch('actUpdateInfo', '显示内容:')
.then(res => {
console.log(res);
console.log('操作成功');
});
}
vuex-modules
- modules属性代表的是模块。当项目过于复杂,通过对项目进行划分,分成几个模块方便管理。modules与store结构类似,有state、mutations、getters、actions等属性
const moduleA = {
state: {},
mutations: {},
actions: {},
getters: {}
}
modules: {
a: moduleA
}
- 在模块中使用state属性时,与store中一致。不同的是,在组件中调用state中的属性时需要添加模块名,格式为:$store.state.a.属性名
<h2>{{$store.state.a.name}}</h2>
- mutations属性与store完全一致,需要注意的是,定义mutations时函数名不能与store中mutations中函数名称重复
- getters属性与在store中类似。在定义getters函数的时候,默认参数为state,还可以将getters属性作为参数传入。不同的是,在模块中的getters属性可以传入第三个参数“rootState”,该参数为store对象中的state属性,可以调用根对象中的state属性
getters: {
fullName(state) {
return state.name + '0000';
},
fullName2(state, getters) {
return getters.fullName + '1111';
},
fullName3(state, getters, rootState) {
return getters.fullName2 + rootState.message;
}
}
<h2>{{$store.getters.fullName}}</h2>
<h2>{{$store.getters.fullName2}}</h2>
<h2>{{$store.getters.fullName3}}</h2>
- actions属性与store中完全一致。不同的是actions中的参数context代表上下文,可以引用“rootState”与“rootGetters”,分别代表根中的state属性与getters属性,也就是store对象中的state属性与getters属性
actions: {
actUpdateName(context) {
console.log(context.rootState);
console.log(context.rootGetters);
setTimeout(() => {
context.commit('updateName', 'Name');
}, 1000);
}
}
actUpdateName() {
this.$store.dispatch('actUpdateName');
}