vuex中的...mapState与...mapMutations的使用以及mapGetters存在的意义
1、mapState、mapGetters在何处使用?区别是什么 ?
无论是state或者getters中的数据,在页面中使用时都是注入到当前的计算属性中。一般是挂在computed里面的,因为如果挂在data上面,只会赋值一次,不会跟着vuex里面的数据变化而同步变化,当然也可以通过watch $store去解决。
mapState、mapGetters都是在computed中直接使用的,那mapGetters还有存在的必要吗?
后者存在的意义是对 state
的计算属性,本质是对 state
中的数据进行一些计算,比例如数据的修饰之类的,这其实是一个代码解耦的过程。如果有做某些数据的格式化处理使用到getter的话,如果只是简单的取数据,赋值,则仅仅是state和mutation足以。但是并不能说 mapGetters
没有存在的意义,只是你把 state
中的数据在 mutation
阶段就处理掉完了(计算),所以就用不到 getters
做计算,只需要直接访问 state
。
2、在页面中通过$store来使用vuex中的数据
①挂在计算属性中,用this.$store.state或this.$store.getters取值
computed: {
hasBg(){
return this.$store.state.hasBg
}
}
②在data中使用,结合watch使得vuex与页面数据同步(不推荐)
data() {
return {
userName:this.$store.state.userName
};
},
watch : {
'$store.state.userName' : {
handler(newVal,oldVal) {
this.userName = newVal
}
}
}
3、使用...mapState与...mapMutation
...mapState与...mapMutation就是第一种方法的简便写法
import { mapState } form 'vuex'
.....
computed: {
//数组的写法:相对于age(){ruturn this.$store.state.age} ps:用引号包着
...mapState(['age','name','sex'])
//对象的写法:若需要重命名则采用对象形式
...mapState({nianling:'age',xingming:'name',xingbie:'sex'})
...mapMutation的使用与...mapState相同,只是放在methods中。借助mapMutations生成对应的方法,方法中会调用commit去联系mutations