详解vue3的setup中通过键值对的方式拿到vuex的state

详解vue3的setup中通过键值对的方式拿到vuex的state

一丶通过普通方式获取vuex中的state

首先引入我们的api

import { useStore } from 'vuex';
import { computed } from 'vue';

然后创建使用

export default {
    setup(){
        // useStore 是一个store对象
        const store = useStore()

        const sCounter = computed(() => store.state.counter)

        return {
            sCounter
        }
    }
}

如果我们一时间要拿多个vuex中的state数据,就是这样

export default {
    setup(){
        // useStore 是一个store对象
        const store = useStore()

        const sCounter = computed(() => store.state.counter)

        const sName= computed(() => store.state.name)

        const sAge= computed(() => store.state.age)

        return {
            sCounter,
            sName,
            sAge
        }
    }
}

如果这样一个一个拿就会很繁琐。

我们可以通过mapState的方法拿,这样子就会很方便

二丶通过mapState Api的方法

先引入api

import { mapState,useStore } from 'vuex';
import { computed } from 'vue';

然后通过mapState的方法获取就是这样

const storeStateFns = mapState(['counter','name','age'])

我们通过es6解析语法导出

return {
  ...storeStateFns
}

然后我们在页面上使用一下 

 我们会发现,它显示出来的都是一个一个函数

因为我们在setup里面使用mapState,它每一个数组里面都是一个函数,然后没有返回值,所有显示的就是一个直接的函数,如果我们在computed api里面使用,它就会自动返回值

我们可以通过一些自己方法,稍微封装一下。因为在vue3官网是没有提到的

我们刚刚提到到:直接解析就是一个个函数,所以我们要使用computed 把它变 一个个ref

通过遍历,拿出一个个函数,然后再解析到computed api里面

这个有一个点需要注意:因为我们setup里面是没有this的

所有我们要通过bind的方法绑定this,并且添加我们的$store进去

 const storeStateFns = mapState(['counter','name','age'])
        // {name:function,counter:function}
        // {name:ref,counter:ref}
        const storeState = {}
        Object.keys(storeStateFns).forEach(fnkey => {
            // bind() 绑定this
            const fn = storeStateFns[fnkey].bind({$store:store});
            storeState[fnkey] = computed(fn)
        })



        return {
            sCounter,
            ...storeState
        }

全部代码

<script>
import { mapState,useStore } from 'vuex';
import { computed } from 'vue';
export default {
    setup(){
        // useStore 是一个store对象
        const store = useStore()

        const sCounter = computed(() => store.state.counter)

        const storeStateFns = mapState(['counter','name'])
        // {name:function,counter:function}
        // {name:ref,counter:ref}
        const storeState = {}
        Object.keys(storeStateFns).forEach(fnkey => {
            // bind() 绑定this
            const fn = storeStateFns[fnkey].bind({$store:store});
            storeState[fnkey] = computed(fn)
        })



        return {
            sCounter,
            ...storeState
        }
    }
}
</script>

码字不容易,如需转载,请注明出处。谢谢各位大哥。

  • 10
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 5
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值