vue3项目开发中,项目里都会在vuex中存储一些公共的资源,方便在各个组件之间使用,大项目中一个.vue文件中可能会用到state里面多个数据,每次都用$store.state.xxx
这样写的话,代码阅读起来也不是很友好。
下面是在vue3中如何使用mapState获取到vuex中state里面的数据
最后面提供了将mapstate封装是hooks,可直接在页面中调用
vuex最新版本安装命令:npminstall vuex@next
store文件
import{ createStore}from'vuex'const store=createStore({state(){return{count:100,name:'code',age:18,}},mutations:{},actions:{}})exportdefault 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'exportdefault{setup(){// setup中是没有this的, 这里使用vue提供的hooks:useStoreconst 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>
创建useState.js文件,里面是封装的mapState
import{ computed}from'vue'import{ mapState, useStore}from'vuex'exportfunctionuseState(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文件'exportdefault{setup(){const storeState=useState(['count','name','age'])return{...storeState}}}</script>