import { useStore, mapState } from 'vuex'
import { computed } from 'vue'
export function useState (mapper) {
  const store = useStore()
  const stateFunObj = mapState(mapper)
  const state = {}
  Object.keys(stateFunObj).forEach(funKey => {
    // bind是为了绑定store setup中没有this 所有函数执行时取不到$store
    state[funKey] = computed(stateFunObj[funKey].bind({$store: store}))
  })
  return state
}

// 使用
import { useState } from './useState.js'

setup () {
  const state = useState(['user']) // useState参数与mapState一致
  return {
    ...state
  }
}

Logo

欢迎加入 MCP 技术社区!与志同道合者携手前行,一同解锁 MCP 技术的无限可能!

更多推荐