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>