vue3中如何从vuex中获取多个state数据呢

2,922 阅读1分钟

你是否也会因为从state中获取多个数据而频繁的写computed和store呢。 我们这里拿name, age举例:

  • 普通获取: 通过computed或者$store获取state的数据,如果要获取多个数据呢,就要写多个computed获取数据,比较繁琐。
<template>
    <h2>{{ $store.state.name }}</h2>
    <h2>{{ sName }}</h2>
</template>

<script>
  import { computed } from 'vue'
  import { useStore } from 'vuex'
  export default {
    setup() {
      const store = useStore()
      // 获取state数据
      const sName = computed(() => store.state.name) 
      const sAge = computed(() => store.state.age)
      const sHeight = computed(() => store.state.height)
      return {
        sName
      }
    }
  }
</script>
  • 获取多个state数据的写法(推荐)

方便简约,可以获取多个state数据。通过coputed的转化,将函数转换成ref形式,解决了获取多个state数据需要频繁写computed的问题。

<template>
    <h2>{{counter}}</h2>
    <h2>{{name}}</h2>
    <h2>{{age}}</h2>
    <h2>{{height}}</h2>
</template>

<script>
  import { computed } from 'vue'
  import { useStore, mapState } from 'vuex'
  export default {
    setup() {
      // 拿到store对象 
      const store = useStore()
      
      // 获取到对应的对象的functions: {name:function, age: function}
      const storeStateFns = mapState(['counter', 'name', 'age', 'height']) 
       
      // 对数据进行转换
      const storeState = {}
      // 遍历key,将函数转换成computed的ref对象
      Object.keys(storeStateFns).forEach(fnKey => {
        const fn = storeStateFns[fnKey].bind({ $store: store }) // 获取this
        storeState[fnKey] = computed(fn) //转成ref
      })
      return {
        ...storeState
      }
    }
  }
</script>