Vue3使用mapstate

2022-03-18 16:12:03

当我们使用vuex中的store中的state的数据值,要通过$store.state.属性名来拿显得麻烦

下边是coderwhy老师的一种方法

简便方法一:(创建计算属性,一个个的提取)

例如以下的counter,最后return {counter}即可

但是属性一旦多起来代码就会变得冗余

简便方法二:(封装useState的hooks)

1.错误示范

这边解释一下为什么不直接导入mapState之后传入computed(比如以下代码,下边是错误示范)

因为mapState返回的是一个个对象,并且每个对象的键值对中,值都是一个个方法,所以显示的都函数。

2.正确示范

 但是我们要达到下边的方法该怎么做

import { computed } from 'vue'
import { mapState, useStore } from 'vuex'
export default function (mapper) { //mapper为传入的数组或者对象
  const store = useStore()   // 获取state对象
  const stateFns = mapState(mapper)
  const stateMaps = {}
  Object.keys(stateFns).forEach((key) => { //遍历数组或者对象,加入计算属性
    // 计算属性接收一个方法,mapState()返回的就是一个键值对,值就是方法
    stateMaps[key] = computed(stateFns[key].bind({ $store: store }))
  })
  return stateMaps
}

但是computed就是接受一个方法,然后返回一个计算属性,这样我们用一个空数组来接收计算属性不久可以了吗,解决。(这边要注意stateFns内部绑定this的问题,需要手动添加一个$store)

3.优化

import { computed } from 'vue'
import { useStore } from 'vuex'
export default function (mapper, func) { //mapper为传入的数组或者对象
  const store = useStore()   // 获取state对象
  const stateFns = func(mapper)
  const stateMaps = {}
  Object.keys(stateFns).forEach((key) => { //遍历数组或者对象,加入计算属性
    // 计算属性接收一个方法,mapState()返回的就是一个键值对,值就是方法
    stateMaps[key] = computed(stateFns[key].bind({ $store: store }))
  })
  return stateMaps
}

import useMapper from './useMapper'
import { mapState } from 'vuex'
export default function (mapper) { 
  return useMapper(mapper, mapState)
}

 这样getters就可以这样写(也就是抽取了公共代码)

那么在mapMutation的喃?

其实直接用就可以了,因为@click接收的就是一个函数,不需要封装

4.模块划分

如果此时module又分了一个模块home,我们该如何使用map喃(mapaction和mapmutation是直接用的),createNamespaceHelper用来确定当前模块(设置为home,这样就直接提交方法即可)。

 这时候就要对第一个参数进行模块划分,多加一个判断即可

import useMapper from './useMapper'
import { mapState, createNamespacedHelpers } from 'vuex'
export default function (moduleName, mapper) {
  let myMapState = mapState
  if (typeof moduleName === "string" && moduleName.length !== 0) {
    myMapState = createNamespacedHelpers(moduleName).mapState
  } else { //如果moduleName没有传入,则只有一个参数,也就是要传入的数组或者对象
    mapper = moduleName
  }
  return useMapper(mapper, myMapState)
}

之前useMapper代码不变

import { computed } from 'vue'
import { useStore } from 'vuex'
export default function (mapper, func) { //mapper为传入的数组或者对象
  const store = useStore()   // 获取state对象
  const stateFns = func(mapper)
  const stateMaps = {}
  Object.keys(stateFns).forEach((key) => { //遍历数组或者对象,加入计算属性
    // 计算属性接收一个方法,mapState()返回的就是一个键值对,值就是方法
    stateMaps[key] = computed(stateFns[key].bind({ $store: store }))
  })
  return stateMaps
}
  • 作者:唱腔ฅ՞•ﻌ•՞ฅ另类:)
  • 原文链接:https://blog.csdn.net/qq_45208029/article/details/121843060
    更新时间:2022-03-18 16:12:03