vue3-setup中使用mapState
vue3项目开发中,项目里会在vuex中存储一些公共的资源,方便在各个组件之间的调用,大项目中一个.vue文件中可能会用到state里面多个数据,每次都用$store.state.xxx这样写的话,代码阅读起来也不是很友好。下面是在vue3中如何使用mapState获取到vuex中store里面的数据最后面提供了将mapstate封装是hooks,可直接在页面中调用vuex最新版本安装命令:npm
·
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(){
// setup中是没有this的, 这里使用vue提供的hooks:useStore
const store = useStore()
// 单个获取vuex中state里面的数据
/* 不推荐 这样写的话会很繁琐,
const sCount = computed(()=>store.state.count)
const sName = computed(()=>store.state.name)
*/
// 推荐
// 在项目中会有很多资源要从vuex的state里获取数据, 下面是提供一个简单的方法
//需要取哪些数据,全部放在数组里即可
const storeStateFns = mapState(['count','name','age'])
// storeStateFns = {count:function(){},name:function(){},age:function(){}}
// 对数据进行转化
const storeState = {}
//对sotreStateFns进行Object.keys(sotreStateFns) = [count,name,age]
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) {
// 拿到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
}
在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>
更多推荐
已为社区贡献4条内容
所有评论(0)