如何使用Vue mapState快捷获取Vuex state多个值
作者:阿淮iya
这篇文章主要为大家介绍了如何使用Vue mapState快捷获取Vuex state多个值实现详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
如何在 Vue3 中更方便快捷地 获取 Vuex 中state 中的多个值
假设 在 state 存在值,需要全部获取
state(){
return {
name:'huai',
age:'18',
height:'180',
sex:'男'
}
}
页面中展示
<p>{{name}}</p>
<p>{{age}}</p>
<p>{{height}}</p>
<p>{{sex}}</p>Vue2 可以直接使用 mapState 直接放到 computed中计算
// vue2
computed:{
...mapState(["name","age","height","sex"]),
}
Vue3 中提供了 useStore() 进行获取
但不能直接像Vue2 那样通过mapState() 进行一次性获取多个值,只能一次获取一个
// vue3
import {computed} from 'vue'
import { useStore} from 'vuex';
setup(){
const store = useStore();
const name = computed(()=>store.state.name);
const age = computed(()=>store.state.age);
const height = computed(()=>store.state.height);
const sex = computed(()=>store.state.sex);
return {
name,
age,
height,
sex
}
}如何在 Vue3 中 使用 mapState() 一次获取vuex中 state 多个值
需要解决的问题:
- 1.setup中没有this 指向
- 2.mapState的返回值
解决办法
mapState 返回值 是一个对象,{name:function,age:function},对象的值是一个函数,恰好computed 的参数可以是函数返回值,只要解决了 computed中的$store 指向就可以,恰好 Vue3提供了 useStore(),然后使用apply() 或者 bind() 进行 指向
import { computed } from 'vue';
import { useStore , mapState } from 'vuex';
setup(){
const store = useStore();
// 传入数组
const storeStateFns = mapState(["name","age","height","sex"]);
const storeState ={};
Object.keys(storeStateFns).forEach(Fnkey => {
// setup中无this 指向,在 compute中计算state时需要 $store 指向 ,所以使用bind() 绑定 $store
const fn = storeStateFns[Fnkey].bind({ $store: store });
storeState[Fnkey] = computed(fn)
})
return{
// 解构
...storeState
}
}封装
// useState.js
import { useStore, mapState } from 'vuex'
import { computed } from 'vue';
export default function(mapper) {
// 获取key,并判断是否存在
const store = useStore();
// 获取相应的对象 : {name:function,age:function}
const storeStateFns = mapState(mapper);
// 进行 $store 指向 ,并赋值
const storeState = {}
Object.keys(storeStateFns).forEach(Fnkey => {
// setup中无this 指向,在 compute中计算state时需要 $store 指向 ,所以使用bind() 绑定 $store
const fn = storeStateFns[Fnkey].bind({ $store: store });
storeState[Fnkey] = computed(fn)
})
// 返回值
return storeState;
}使用
import hookStoreState from './useState.js'
export default {
setup() {
// 传入数组
const storeStateArr = hookStoreState(["name", "age", "counter"]);
// 传入对象,可以避免参数名重复
const storeStateObj = hookStoreState({
sName: (state) => state.name,
sAge: (state) => state.age,
sHeight: (state) => state.height,
sSex:(state)=>state.sex
});
return {
...storeStateArr,
...storeStateObj,
};
},
};以上就是如何使用Vue mapState快捷获取Vuex state多个值的详细内容,更多关于Vue mapState使用的资料请关注脚本之家其它相关文章!
