vuex提供了辅助函数处理庞大的vuex数据,mapState,mapGetters,mapMutations,mapActions,实际就是把state、getters、mutations、actions整合成一个数组,一次性返回
注:mapState,mapGetters返回的是属性,所以混入到 computed 中,mapMutations,mapActions返回的是方法,只能混入到methods中
<template>
<div v-if="user.userName">
<span>欢迎您:{{user.userName}}</span>
</div>
</template>
<script>
import {mapState,mapGetters,mapMutations,mapActions} from 'vuex'
export default {
name: 'App',
mounted(){
console.log(mapGetters(['user']).user.call(this))
},
computed:{
...mapGetters(['user']), //mapGetters(['user'])返回this.$store.getters.user对象,相当于以下代码
// user(){
// return this.$store.getters.user
// }
}
}
</script>
使用辅助函数是把vuex中的getters等函数映射到vue中,调用时使用 this.user 即可调用 this.$store.getters.user 函数,传参时正常传参
注意:你在组件中可以使用 this.$store.dispatch('xxx')
分发 action,或者使用 mapActions
辅助函数将组件的 methods 映射为 store.dispatch
调用
import { mapActions } from 'vuex'
export default {
// ...
methods: {
...mapActions([
'increment' // 映射 this.increment() 为 this.$store.dispatch('increment')
]),
...mapActions({
add: 'increment' // 映射 this.add() 为 this.$store.dispatch('increment')
})
}
}
...mapState('命名空间名', ["permissionList"])