//你还可以在这里执行其他的操作改变state
}
}
}
使用 mutations 后 , 原先我们的父组件可以改为 :
<template>
<div id="app">
<a href="javascript:;" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" @click="$store.commit('switch_dialog')">点击</a>
<t-dialog></t-dialog>
</div>
</template><script>
import dialog from './components/dialog.vue'
export default {
components:{
"t-dialog":dialog
}
}
</script>
使用 $store.commit(‘switch_dialog’) 来触发 mutations 中的 switch_dialog 方法。
这里需要注意的是:
1、mutations 中的方法是不分组件的 , 假如你在 dialog_stroe.js 文件中的定义了
switch_dialog 方法 , 在其他文件中的一个 switch_dialog 方法 , 那么
$store.commit(‘switch_dialog’) 会执行所有的 switch_dialog 方法。
2、mutations里的操作必须是同步的。
你一定好奇 , 如果在 mutations 里执行异步操作会发生什么事情 , 实际上并不会发生什么奇怪的事情 , 只是官方推荐 , 不要在 mutationss 里执行异步操作而已。
actions
多个 state 的操作 , 使用 mutations 会来触发会比较好维护 , 那么需要执行多个 mutations 就需要用 action 了:
export default {
state:{//state
show:false
},
mutations:{
switch_dialog(state){//这里的state对应着上面这个state
state.show = state.show?false:true;
//你还可以在这里执行其他的操作改变state
}
},
actions:{
switch_dialog(context){//这里的context和我们使用的$store拥有相同的对象和方法
context.commit('switch_dialog');
//你还可以在这里触发其他的mutations方法
},
}
}那么 , 在之前的父组件中 , 我们需要做修改 , 来触发 action 里的 switch_dialog 方法:
<template>
<div id="app">
<a href="javascript:;" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" @click="$store.dispatch('switch_dialog')">点击</a>
<t-dialog></t-dialog>
</div>
</template><script>
import dialog from './components/dialog.vue'
export default {
components:{
"t-dialog":dialog
}
}
</script>
使用 $store.dispatch(‘switch_dialog’) 来触发 action 中的 switch_dialog 方法。
官方推荐 , 将异步操作放在 action 中。
getters
getters 和 vue 中的 computed 类似 , 都是用来计算 state 然后生成新的数据 ( 状态 ) 的。










