state
用于存储共享数据
Vuex.Store({
state: {
count: 0
}
})
//xxx.vue 文件中使用
this.$store.state.count
//更改
this.$store.state.count = 1; //不推荐
mutations
需要注意的是vue 建议mutations处理同步函数,因为方便devtool监听其变化,以便更好的调试开发
更严格的用法是mutations不允许出现副作用函数
Vuex.Store({
state: {
count: 0
},
mutations: {
INCREASE(state) {
state.count++;
},
DECREASE(state) {
state.count--;
},
POWER(state, payload) {
//payload --> 负载,载荷 调用时附带的参数
state.count **= payload;
//通常可以将payload写成一个对象 {type: "POWER", number: 3};
// state.count **= payload.number;
}
}
})
//在文件中使用
this.$store.commit("INCREASE");
this.$store.commit("INCREASE"); // count = 2
this.$store.commit("POWER", 3); //count = 8 或者 对象写法
this.$store.commit({type: "POWER", number: 3});
actions
通常用于异步,返回一个Promise对象
function delay(duration) {
return new Promise(resolve => {
setTimeout(()=> {
resolve();
}, duration)
})
}
Vuex.Store({
state: {
count: 0
},
mutations: {
INCREASE(state) {
state.count++;
},
DECREASE(state) {
state.count--;
},
POWER(state, payload) {
//payload --> 负载,载荷 调用时附带的参数
state.count **= payload;
//通常可以将payload写成一个对象 {type: "POWER", number: 3};
// state.count **= payload.number;
},
MULTIPLE_NAME() {}
},
actions: {
//通常写法
async increase({ commit }) {
await delay(1000);
commit("INCREASE");
},
async decrease({ commit }) {
await delay(1000);
commit("DECREASE");
},
async power({ commit }, payload) {
//payload的支持方式与mutation相同
await delay(1000);
commit("POWER", payload); //payload未传对象
// commit("POWER", payload.number); //payload传带有type对象
},
multipleName() {}
}
})
//文件中调用
this.$store.dispatch("increse"); // 等待一秒 1
this.$store.dispatch("increse"); // 等待一秒 2
this.$store.dispatch("power", 3); //等待一秒 8 或者带type的对象写法
this.$store.dispatch({type: "power", number: 3})