异步
在mutation中是不能执行异步操作的,如果我们需要异步处理,则必须通过vuex中的Action中来处理
声明Action
const store = new VueX.Store({
mutations:{ change(state,参数C){ state.cc=234, alert(11); } },
actions:{
事件名A(参数B,参数C){
setTimeout(()=>{
参数B.commit(‘change’)
},1000) } }
})
触发Action
在组件的方法中写入
this.$store.dispatch(‘事件A’,参数C )
在Action中不能直接修改数据,需要调用mutation中的事件,使用 参数B.commit(‘函数’)
第二种触发方法
import {mapActions} from ‘vuex’
methods:{
…mapAction([actionA,actionB…])
}
Getter
对store的数据进行加工形成新数据(不影响原数据)
定义getter与其他相似
getters:{
mygetter(state){
return 处理后的数据
}}
使用getter
this.$store.getters.mygetter
Module
module可以将一个store分割为多个不同的部分,每一个module,可以拥有自己的 state、mutation、action、getter,相当于内部的一个store
const moduleA = {
state: () => ({ ... }),
mutations: { ... },
actions: { ... },
getters: { ... }
}
const moduleB = {
state: () => ({ ... }),
mutations: { ... },
actions: { ... }
}
const store = new Vuex.Store({
modules: {
a: moduleA,
b: moduleB
}
})
store.state.a // -> moduleA 的状态
store.state.b // -> moduleB 的状态
对于模块内部的 mutation 和 getter,接收的第一个参数是模块的局部状态对象,即是模块store
根节点则通过context.rootState暴露出来
关于更多的vuex可以看vue的官方文档,非常详细的https://vuex.vuejs.org/zh/installation.html