辅助函数简化了获取store中的state、getters、mutations、actions,使用方法如下:
首先在组件中的script引入
//需要哪个引入哪个即可
import { mapState, mapGetters, mapMutations, mapActions } from 'vuex'
因为state和getters返回的是属性,也就是具体的值,所以mapState和mapGetters应该放在计算属性computed中。
//home.vue
<div>{{ name }}{{ getName }}</div>
computed:{
...mapState(['name']) // =>this.$store.state.name
...mapGetters(['getName']) // =>this.$store.getters.getName
}
因为mutations和actions返回的是函数,所以应该放在组件的methods属性中。
mounted(){
this.setName(传参)
},
methods:{
...mapMutations(['setName'])
}