vue3项目开发中,项目里都会在vuex中存储一些公共的资源,方便在各个组件之间使用,大项目中一个.vue文件中可能会用到state里面多个数据,每次都用 $store.state.xxx 这样写的话,代码阅读起来也不是很友好。 下面是在vue3中如何使用mapState获取到vuex中state里面的数据
最后面提供了将mapstate封装是hooks,可直接在页面中调用
vuex最新版本安装命令:npm install vuex@next
store文件
import { createStore } from 'vuex'
const store = createStore({
state(){
return {
count: 100,
name: 'code',
age:18,
}
},
mutations:{
},
actions:{
}
})
export default store
vue页面中使用
<template>
<div>
<h2>{{sCount}}</h2>
<h2>{{sName}}</h2>
<hr>
<h2>{{count}}</h2>
<h2>{{name}}</h2>
<h2>{{age}}</h2>
</div>
</template>
<script>
import { computed ,} from 'vue'
import { mapState, useStore } from 'vuex'
export default {
setup(){
const store = useStore()
const storeStateFns = mapState(['count','name','age'])
const storeState = {}
Object.keys(storeStateFns).forEach(fnKey => {
const fn = storeStateFns[fnKey].bind({$store:store})
storeState[fnKey] = computed(fn)
})
return {
sCount,
sName,
...storeState
}
}
}
</script>
把mapState封装成一个hooks,方便页面中调用
创建useState.js文件,里面是封装的mapState
import { computed } from 'vue'
import { mapState, useStore } from 'vuex'
export function useState(mapper) {
const store = useStore()
const storeStateFns = mapState(mapper)
const storeState = {}
Object.keys(storeStateFns).forEach(fnKey => {
const fn = storeStateFns[fnKey].bind({$store: store})
storeState[fnKey] = computed(fn)
})
return storeState
}
在setup中使用封装好的mapState
<template>
<div>
<h2>{{count}}</h2>
<h2>{{name}}</h2>
<h2>{{age}}</h2>
</div>
</template>
<script>
import {useState} from '引入刚刚封装的useState.js文件'
export default {
setup(){
const storeState = useState(['count','name','age'])
return {
...storeState
}
}
}
</script>
|