vue3-setup中使用mapState

本文介绍了在Vue3项目中如何利用Vuex进行状态管理,特别是如何通过mapState简化组件中获取state数据的过程,并展示了如何封装一个自定义的useState hooks,以便更便捷地在页面中调用Vuex的state数据。
摘要由CSDN通过智能技术生成

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
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值