每天记录一个小知识8:vue2与vue3中store变量数据的获取

vue2

详情说明查看:状态管理Vuex | uni-app官网

这里记录两条较为常用的方法:

1.通过 this.$store 访问到 state 里的数据

<!-- 页面路径:pages/index/index.vue -->
<template>
	<view>
		<text>用户名:{{username}}</text>
        <text>年龄:{{age}}</text>
	</view>
</template>
<script>
	export default {
		data() {
			return {}
		},
		computed: {
			username() {
				return this.$store.state.username 
			},
            age() {
				return this.$store.state.age
			},

		}
	}
</script>

2.通过 mapState 辅助函数获取

<!-- 页面路径:pages/index/index.vue -->
<template>
	<view>
		<view>用户名:{{username}}</view>
		<view>年龄:{{age}}</view>
	</view>
</template>
<script>
	import { mapState } from 'vuex'//引入mapState
	export default {
		data() {
			return {}
		},
		computed(){
            //另一种写法
            //...mapState({
		        // 从state中拿到数据 箭头函数可使代码更简练
		       // username: state => state.username,
			   // age: state => state.age,
		    //}) 
             ...mapState(['username', 'age'])
        } 
	}
</script>

vue3

1.结合mapState和computed在Vue3版本中的setup使用

1.封装mapState

//新建utils/useMapState.js
import { computed } from "vue"
import { mapState, useStore } from "vuex"
export default function (state) {
    // 1. 获取实例 $store
    const store = useStore()
    // 2. 遍历状态数据
    const storeStateFns = mapState(state)
    // 3. 存放处理好的数据对象
    const storeState = {}
    // 4. 对每个函数进行computed
    Object.keys(storeStateFns).forEach(fnKey => {
        const fn = storeStateFns[fnKey].bind({ $store: store })
        // 遍历生成这种数据结构 => {name: ref(), age: ref()}
        storeState[fnKey] = computed(fn)
    })
    return storeState
}

2.页面使用方法

<template>
	<view class="viewBox">{{myState.name}}</view>
</template>

<script setup>
    import useMapState from "@/utils/useMapState.js"
    //1.传对象
    //const myState = useMapState({
	//    name: state => state.modulesA.name,
	//})
    //2.传数组
     const myState = useMapState(['name', 'age', 'counter'])
</script>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值