前言
今天给大家分享一个学习到的vue3自己封装获取大量store中数据的方法,希望能帮到各位掘友
vue2写法
我们在vue2中大部分都是使用this.$store.state方法或者是利用mapState辅助函数去获取仓库中存储的数据
// store下的index.js文件
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
// 数据定义的位置
state: {
// 用户数据
userInfo: {}
},
mutations: {
}
},
actions: {},
modules: {}
})
<script>
// 导入 mapState
import { mapState } from 'vuex'
// 1.computed使用辅助函数获取数据
computed: mapState(['userInfo'])
// 2.这是使用this.$store方法
computed: {
userInfo () {
return this.$store.state.userInfo
}
}
</script>
vue3写法
vue3中没有了this,使用的是composition API,所以我们需要的是先导入后使用,而且vue3中也不推荐使用辅助函数去获取仓库中存取的数据了
<template>
<div>
<h2>仓库数据{{ $store.state.userInfo }}</h2>
<hr>
<h2>{{myUserInfo}}</h2>
</div>
</template>
<script>
import { mapState, useStore } from 'vuex'
import { computed } from 'vue'
export default {
// 这里也支持用vue2的computed来使用辅助函数
setup(){
const store = useStore()
// 平时我们使用的方法
const myUserInfo = computed(()=> store.state.counter)
return{
myUserInfo
}
}
}
</script>
这种方法在少量数据是取用比较方便,但是如果数据多了,代码长而且冗余,所以我们需要思考一下怎么样可以像辅助函数一样大量获取,在vue2中computed可以使用...mapState来结构
既然我们可以使用computed(()=> store.state.counter)的方式来获取单个,那我们是不是也可以考虑使用遍历的方法来获取多个
setup () {
const store = useStore()
const myUserInfo = computed(()=>{store.state.userInfo})
// 取出函数
const storeState = mapState(['userInfo','name','age',])
// 定义一个空对象存储
const allState = {}
Object.keys(storeState).forEach(key=>{
// 需要绑定$store
const fn = storeState[key].bind({$store: store})
allState[key] = computed(fn)
})
return{
myUserInfo,
...allState
}
}
封装方法
我们不可能每个页面都去写这些代码,所以我们需要封装一下,让我们所有页面都只要导入方法就可以使用
// 文件命名为useState
import { computed } from 'vue'
import { mapState, useStore } from 'vuex'
export function useState(mapper) {
// 拿到store独享
const store = useStore()
// 获取到对应的对象的functions: {name: function, age: function}
const storeStateFns = mapState(mapper)
// 对数据进行转换
const storeState = {}
Object.keys(storeStateFns).forEach(fnKey => {
const fn = storeStateFns[fnKey].bind({$store: store})
storeState[fnKey] = computed(fn)
})
return storeState
}
结尾
可能有些同学学过这些,但是我只是记录一下学习的东西,希望大家有所帮助,每天进步一点点,早日拿到满意的薪资