vue3 在setup中使用mapSate以及对mapState的封装

vue3 在setup中使用mapSate以及对mapState的封装,第1张

在setup中使用mapSate
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
	 }
}

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/1322300.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-12
下一篇 2022-06-12

发表评论

登录后才能评论

评论列表(0条)

保存