在composition API 中使用mapState
1 setup() {
2 const store = useStore()
3
4 const sCounter = computed(() => store.state.counter)
5
6 // 都是函数
7 const storeStateFns = mapState(['counter', 'name', 'age'])
8 // 存放computed处理后的ref
9 const storeState = {}
10 Object.keys(storeStateFns).forEach(fnKey => {
11 /* mapState() 本质上就是 this.$store.state来获取 所以这里要对mapState返回的函数重新进行this的绑定
12 在bind中添加一个对象 此时this就指向这个对象 在对象中添加$store 并将hook中获取到的store保存
13 就是实现了mapState() 中每一个单独的函数的实际操作 */
14 const fn = storeStateFns[fnKey].bind({$store: store})
15 // 这一步相当于把每个函数放入computed处理返回ref
16 storeState[fnKey] = computed(fn)
17 })
18
19 return {
20 sCounter,
21 ...storeState
22 }