1. 在 Vue3的setup中 获得 Vuex 中 state 状态 和 getters
1.1 封装一个useMapper函数
// import { computed } from 'vue'
// import { mapState, useStore } from 'vuex'
// export function useState(mapper) {
// // 拿到store独享
// const store = useStore()
// // 获取到对应对象的functions : {name:function,age:function}
// const stateFns = mapState(mapper)
// // 对数据进行转换
// let storeState = {}
// Object.keys(stateFns).forEach(fnKey => {
// let fn = stateFns[fnKey].bind({$store : store})
// storeState[fnKey] = computed(fn)
// })
// return storeState
// }
import { computed } from 'vue'
import { useStore } from 'vuex'
export function useMappers(mappers, mapFn){ // mapFn 表示要使用的是 mapState 还是 mapGetters 辅助函数
const store = useStore()
const mapperFns = mapFn(mappers)
let storeMappers = {}
Object.keys(mapperFns).forEach(fnKey => {
let fn = mapperFns[fnKey].bind({$store : store})
storeMappers[fnKey] = computed(fn)
})
return storeMappers
}
- useMappers(mappers, mapFn);mappers传入的是数组,里面是字符串,后面是辅助函数;类似于 useMappers(['name', 'age', 'sex'],mapState)
- let fn = mapperFns[fnKey].bind({$store : store})要绑定this,这样才可以在拿的时候
- 在使用的时候,引入useMappers就行啦,记得导入mapState和mapGetters
<!-- 封装的state方法 -->
storeState: {{ name }} - {{ age }} - {{ sex }}
totalPrice-getters: {{ totalPrice }}
import { useMappers } from './hooks/useState' // 引入自己封装的useMappers方法
import { mapState,mapGetters } from 'vuex' // 引入辅助函数 mapState和mapGetters 根据自己需要
setup(){
// 封装的state方法
const storeState = useMappers(['name', 'age', 'sex'],mapState)
const totalPrice = useMappers(['totalPrice'], mapGetters)
return{
...storeState,
...totalPrice
}
}
网友评论