前言
传统的vue2中我们使用optionsAPI使用mapstate很方便,但是vue3使用setup函数中我们想使用mapstate变得比较繁琐,今天我们来封装一个简单的hook,帮助我们方便的在setup中使用mapstate来进行开发,废话不多说,直接看源码吧。
源码(附解释)
很简单,看看就懂了,大家可以直接拿到项目中使用
//useMapState.js hook
import { useStore, mapState } from "vuex"
import { computed } from "vue"
export function useMapState(mapper) {
// 拿到store独享
const store = useStore()
// 获取到对应的对象的functions: {name: function, age: function}
const storeStateFns = mapState(mapper)
const storeState = {}
// 对数据进行转换
Object.keys(storeStateFns).forEach(fnKey => {
//这里绑定this的原因是computed计算属性在进行查找的时候默认会采用this.$store
//由于setup中没有this绑定(this是undefined),所以我们需要调用bind手动进行绑定
const fn = storeStateFns[fnKey].bind({ $store: store })
storeState[fnKey] = computed(fn)
})
return storeState
}
使用
<template>
<div>
<h2>two组件</h2>
<h2>使用hook定义的useMapState:{{counter}}--{{age}}--{{name}}--{{height}}</h2>
<h2>对象写法{{Scounter}}--{{Sname}}</h2>
</div>
</template>
<script>
import {useMapState} from "../hook/useMapState"
export default {
setup(){
const storeState = useMapState(['counter','name','age','height'])
const storeState1 = useMapState({
Scounter:stete => stete.counter,
Sname:state => state.name
})
return{
...storeState,
...storeState1,
}
}
}
</script>
<style scoped>
</style>