context.commit('switch_dialog');
//你还可以在这里触发其他的mutations方法
},
}
}
那么 , 在之前的父组件中 , 我们需要做修改 , 来触发 action 里的 switch_dialog 方法
<template>
<div id="app">
<a href="javascript:;" 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 然后生成新的数据 ( 状态 ) 的
假如我们需要一个与状态 show 刚好相反的状态 , 使用 vue 中的 computed 可以这样算出来
computed(){
not_show(){
return !this.$store.state.dialog.show;
}
}
那么 , 如果很多很多个组件中都需要用到这个与 show 刚好相反的状态 , 那么我们需要写很多很多个 not_show , 使用 getters 就可以解决这种问题
export default {
state:{//state
show:false
},
getters:{
not_show(state){//这里的state对应着上面这个state
return !state.show;
}
},
mutations:{
switch_dialog(state){//这里的state对应着上面这个state
state.show = state.show?false:true;
//你还可以在这里执行其他的操作改变state
}
},
actions:{
switch_dialog(context){//这里的context和我们使用的$store拥有相同的对象和方法
context.commit('switch_dialog');
//你还可以在这里触发其他的mutations方法
},
}
}
我们在组件中使用 $store.state.dialog.show 来获得状态 show , 类似的 , 我们可以使用 $store.getters.not_show 来获得状态 not_show
注意 : $store.getters.not_show 的值是不能直接修改的 , 需要对应的 state 发生变化才能修改
六、mapState、mapGetters、mapActions
很多时候 , $store.state.dialog.show 、 $store.dispatch(‘switch_dialog’) 这种写法很不方便
使用 mapState 、 mapGetters 、 mapActions 就不会这么复杂了
<template>
<el-dialog :visible.sync="show"></el-dialog>
</template><script>
import {mapState} from 'vuex';
export default {










