当前位置:
首页
文章
前端
详情

Vue3 使用mapState

如何在 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>
  1. Vue2 可以直接使用 mapState 直接放到 computed中计算
// vue2 
computed:{
    ...mapState(["name","age","height","sex"]),
}

2.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
    }
}
  1. 如何在 Vue3 中 使用 mapState() 一次获取vuex中 state 多个值呢,
    3.1. 需要解决的问题: 1.setup中没有this 指向 2.mapState的返回值
    3.2. 解决办法
    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,
    };
  },
};

免责申明:本站发布的内容(图片、视频和文字)以转载和分享为主,文章观点不代表本站立场,如涉及侵权请联系站长邮箱:xbc-online@qq.com进行反馈,一经查实,将立刻删除涉嫌侵权内容。