还是前面的例子 , 假如我们需要一个与状态 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’) 这种写法又长又臭 , 很不方便 , 我们没使用 vuex 的时候 , 获取一个状态只需要 this.show , 执行一个方法只需要 this.switch_dialog 就行了 , 使用 vuex 使写法变复杂了 ?
使用 mapState、mapGetters、mapActions 就不会这么复杂了。
以 mapState 为例 :
<template>
<el-dialog :visible.sync="show"></el-dialog>
</template><script>
import {mapState} from 'vuex';
export default {
computed:{
//这里的三点叫做 : 扩展运算符
...mapState({
show:state=>state.dialog.show
}),
}
}
</script>
相当于 :
<template>
<el-dialog :visible.sync="show"></el-dialog>
</template><script>
import {mapState} from 'vuex';
export default {
computed:{
show(){
return this.$store.state.dialog.show;
}
}
}
</script>
mapGetters、mapActions 和 mapState 类似 , mapGetters 一般也写在 computed 中 , mapActions 一般写在 methods 中。
弄懂上面这些 , 你可以去看vuex文档了 , 应该能看懂了。
以上就是vuex入门最详细整理的详细内容,更多关于vuex入门知识点的资料请关注软件开发网其它相关文章!










