vuex中的辅助函数怎么使用?
参考答案
是什么
Vuex 提供 mapState / mapGetters / mapMutations / mapActions 四个辅助函数,把 store 的读写映射到组件的 computed / methods,减少重复的 this.$store.xxx 样板。
用法
import { mapState, mapGetters, mapMutations, mapActions } from 'vuex'
export default {
computed: {
// 数组形式:同名映射
...mapState(['token', 'userInfo']),
...mapState({ myCount: 'count' }), // 别名
...mapState({ count: s => s.module.count }), // 函数式
...mapGetters(['totalPrice', 'cartCount']),
...mapGetters({ price: 'totalPrice' }),
// 命名空间模块
...mapState('user', ['token']),
...mapGetters('cart', ['total']),
},
methods: {
...mapMutations(['SET_TOKEN', 'addItem']), // 需要自己 commit
...mapMutations('cart', { addOne: 'ADD_ITEM' }), // 事件名映射到 mutation 名
...mapActions(['login', 'fetchList']), // dispatch
...mapActions('user', { doLogin: 'login' }),
},
}
原理
function mapState(states) {
const res = {}
normalizeMap(states).forEach(({ key, val }) => {
res[key] = function mappedState() {
const state = this.$store.state
const getters = this.$store.getters
return typeof val === 'function' ? val.call(this, state, getters) : state[val]
}
})
return res
}
function mapMutations(mutations) {
const res = {}
normalizeMap(mutations).forEach(({ key, val }) => {
res[key] = function mappedMutation(...args) {
return this.$store.commit(val, ...args)
}
})
return res
}
即:生成 computed(读)与 methods(写),normalizeMap 把数组/对象统一成 [{key, val}]。
注意
mapMutations/mapActions生成的是方法,必须放在methods里(或setup里返回);- 命名空间模块要带模块名(或使用
createNamespacedHelpers); - 别名冲突时用对象形式重命名;
- Vue 3 + Pinia 没有这套辅助函数,用
storeToRefs解构state/getters,store.action()直接调用。