import { mapState, useStore } from 'vuex'
import { computed } from 'vue'
export default {
name: 'App',
components: {
},
setup() {
const store = useStore()
// 用法1
const sCounter = computed(() => store.state.counter)
// 用法2
const storeStateFns = mapState(["counter", "name"])
// {counter: function, name: function} // 这里每一个对应的都是一个函数,所以不能直接用storeSate
const storeState = {}
Object.keys(storeStateFns).forEach(fnKey => {
const fn = storeStateFns[fnKey].bind({$store: store});
storeState[fnKey] = computed(fn)
})
return {
store,
sCounter,
...storeState
}
},
}
封装一个mapState的hooks
1.先创建一个js文件useState.js
import { computed } from 'vue'
import { mapState, useStore } from 'vuex'
export function useState(mapper) {
// 拿到store对象
const store = useStore()
// 获取到对应的对象的functions
const storeStateFns = mapState(mapper)
// 对数据进行转换
const storeState = {}
Object.keys(storeStateFns).forEach(fnKey => {
const fn = storeStateFns[fnKey].bind({$store: store});
storeState[fnKey] = computed(fn)
})
return storeState
}
2.在页面引用
import { useState } from './hooks/useState.js'
setup(){
const storeState1 = useState(['counter', 'name', 'age'])
const storeState2 = useState({
sCounter: state => state.counter,
sName: state => state.name
})
return {
...storeState1,
...storeState2
}
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)