如何使用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使用的资料请关注脚本之家其它相关文章!
相关文章
vue-cli3.0如何使用CDN区分开发、生产、预发布环境
这篇文章主要介绍了vue-cli3.0如何使用CDN区分开发、生产、预发布环境,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧2018-11-11
vue代理请求之Request failed with status code 404问题及解决
这篇文章主要介绍了vue代理请求之Request failed with status code 404问题及解决方案,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教2023-07-07
Vue中的无限加载vue-infinite-loading的方法
本篇文章主要介绍了Vue中的无限加载vue-infinite-loading的方法,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧2018-04-04
VueJS 集成 Medium Editor的示例代码 (自定义编辑器按钮)
本篇文章主要介绍了VueJS 集成 Medium Editor的示例代码 (自定义编辑器按钮),具有一定的参考价值,有兴趣的可以了解一下2017-08-08


最新评论