mapState和computed结合在Vue3版本中的setup使用
引用地址:https://blog.csdn.net/qq_41308489/article/details/121534153简单的用法: 直接用computed (不推荐)import {computed} from "vue"import {mapState, useStore} from "vuex"export default {setup() {const store = useSto
引用地址:https://blog.csdn.net/qq_41308489/article/details/121534153
简单的用法: 直接用computed (不推荐)
import {computed} from "vue"
import {mapState, useStore} from "vuex"
export default {
setup() {
const store = useStore()
const counter = computed(() => store.state.counter)
return {
counter
}
}
}
如果直接用computed的话,后面如果还有很多状态的情况下,你就要写下面这样子的Bad code
const counter = computed(() => store.state.counter)
const name = computed(() => store.state.name)
const age= computed(() => store.state.age)
const counter = computed(() => store.state.counter)
const counter = computed(() => store.state.counter)
神奇的用法: 结合mapState和computed (推荐!拿来吧你!)
import {mapState, useStore} from "vuex"
import {computed} from "vue"
export default {
setup() {
const store = useStore()
const storeStateFns = mapState(['name', 'age', 'gender'])
/**
* mapState返回的数据结构:
* {
* name: function(){return 'xxx'},
* age: function(){return 'xxx'}
* }
*/
const storeState = {}
Object.keys(storeStateFns).forEach(fnKey => {
// mapState在解析state的数据时,是需要通过this.$store去解析
// 在setup里面是没有this的,所以我们给它的函数绑定ctx
// this => {$store: store}
const fn = storeStateFns[fnKey].bind({$store: store})
// 遍历生成这种数据结构 => {name: ref(), age: ref()}
storeState[fnKey] = computed(fn)
})
return {
...storeState
}
}
}
现在可以在template获取对应的状态数据
<template>
<h2>setup Name: {{name}}</h2>
<h2>setup Age: {{age}}</h2>
<h2>setup Gender: {{gender}}</h2>
</template>
1
2
3
4
5
为了方便使用封装为hook
useMapState.js
import { computed } from "vue"
import { mapState, useStore } from "vuex"
export default function (state) {
// 1. 获取实例 $store
const store = useStore()
// 2. 遍历状态数据
const storeStateFns = mapState(state)
// 3. 存放处理好的数据对象
const storeState = {}
// 4. 对每个函数进行computed
Object.keys(storeStateFns).forEach(fnKey => {
const fn = storeStateFns[fnKey].bind({ $store: store })
// 遍历生成这种数据结构 => {name: ref(), age: ref()}
storeState[fnKey] = computed(fn)
})
return storeState
}
使用方式(数组和对象都可食用)
传入数组形式
import useMapState from "./hooks/useMapState"
export default {
setup() {
const state = useMapState(['name', 'age', 'counter'])
return {
...state,
}
}
}
传入对象形式
import useMapState from "./hooks/useMapState"
export default {
setup() {
const myState = useMapState({
myName: state => state.name,
myAge: state => state.age
})
return {
...myState
}
}
}
更多推荐
所有评论(0)