详解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>

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

Logo

前往低代码交流专区

更多推荐