vuex-setup中封装useState. 详情想看上一篇文章哦。上一篇链接:juejin.cn/post/706665…
一. state中放入几个数据
import { createStore } from 'vuex'
const store = createStore({
state() {
return {
counter: 10,
name: '明明',
age: 18,
height: 1.88
}
}
})
export default store
二. 封装 useState.js
import { computed } from 'vue'
import { useStore, mapState } from 'vuex'
// 封装 获取vuex中state数据的函数
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
}
到现在就封装好啦,让我们开始使用useState。 useState传入数组或者对象都可以。
三.使用封装好的useState
- App.vue引用useState.js
<template>
<h2>{{counter}}</h2>
<h2>{{name}}</h2>
<h2>{{age}}</h2>
<h2>{{height}}</h2>
<hr>
<h2>{{sCounter}}</h2>
<h2>{{sAge}}</h2>
</template>
<script>
// 引用封装好的函数获取vuex中的state数据
import { useState } from '../hooks/useState'
export default {
setup() {
// 使用封装好的函数获取vuex中的state数据
// 数组写法
const storeStore = useState(['counter', 'name', 'age', 'height'])
// 对象写法
const storeStore2 = useState({
sCounter: state => state.counter,
sAge: state => state.age
})
return {
...storeStore,
...storeStore2
}
}
}
</script>