封装一个在setup中使用剩余参数获取vuex数据的hook

152 阅读1分钟
1.首先我们在vuex有如下数据
  state() {
    return {
      counter: 888,
      name: 'why',
      age: 18,
      height: 1.88
    }
  },
2.我们在hooks封装了useState,如果想在组件的setup中一次性获取上面的数据,则通过该方法在数组中传递参数名称,然后展开获取到的对象即可。

2.1 hooks代码

import { computed } from 'vue'
import { mapState, useStore } from 'vuex'
export function useState(mapper) {
  // 拿到store对象
  const store = useStore()
  // 获取对应的对象的function 例如:{name:function, age:function}
  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.2 使用方法:传递参数(属性名称)return中展开对象即可

import { useState } from '../hooks/useState'
export default {
  setup() {
    const storeState = useState(['counter', 'name', 'age', 'height'])
    return {
      ...storeState
    }
  }
};

2.3 使用数据

<template>
  <div>
    <h2>Home:{{ counter }}--{{ name }}--{{ age }}--{{ height }}</h2>
  </div>
</template>