Vue3中封装setup函数中的mapstate改进封装
由于在vue3 compositionApi中 setup函数无法获取this,在使用vuex的时候获取this.$store.state.xx会比较繁琐,而vuex中的函数mapState返回值为函数类型,无法使用computed直接返回具体的数值(会提示缺失$stote),考虑使用bind函数重新封装mapState返回的函数,通过bind指定一个绑定$store,参数为useStore,从而变成可以被computed调用的函数,返回的直接为ref对象从而在template中直接使用
import { computed } from 'vue'
import { mapState, useStore } from 'vuex';
export function useState(arr) {
const store = useStore()
const storeStateFns = mapState(arr)
const storeState = {}
Object.keys(storeStateFns).forEach(key => {
const fn = storeStateFns[key].bind("$store", store)
//执行fn 实质上仍然 执行$store 但无法获取 只能useStore获取-》每个函数绑定this
storeState[key] = computed(fn)
})
return storeState
};

浙公网安备 33010602011771号