Uniapp 全局状态管理实现方案
在 Uniapp 中实现全局状态管理有以下几种常用方法:
1. Vuex 状态管理(推荐)
Vuex 是 Vue 的官方状态管理库,适用于复杂应用的状态管理。
安装与配置
- 在项目中安装 Vuex:
npm install vuex --save
- 创建 store 目录结构:
├── store
│ ├── index.js # 主入口文件
│ ├── modules # 模块目录
│ │ ├── user.js # 用户模块
│ │ └── cart.js # 购物车模块
- 主入口文件示例 (
store/index.js
):
import Vue from 'vue'
import Vuex from 'vuex'
import user from './modules/user'
import cart from './modules/cart'
Vue.use(Vuex)
const store = new Vuex.Store({
modules: {
user,
cart
}
})
export default store
- 在
main.js
中引入:
import store from './store'
const app = new Vue({
store,
...App
})
使用示例
// 在组件中使用
export default {
computed: {
// 获取状态
username() {
return this.$store.state.user.username
}
},
methods: {
// 提交 mutation
updateUsername() {
this.$store.commit('user/SET_USERNAME', 'newName')
},
// 分发 action
fetchUserInfo() {
this.$store.dispatch('user/fetchUserInfo')
}
}
}
2. 全局变量和事件总线
对于小型应用,可以使用简单的全局变量和事件总线:
全局变量
在 main.js
中定义:
Vue.prototype.$globalData = {
userInfo: null,
token: ''
}
组件中使用:
this.$globalData.userInfo = {name: 'John'}
事件总线
在 main.js
中创建:
Vue.prototype.$eventBus = new Vue()
组件中使用:
// 发送事件
this.$eventBus.$emit('user-login', userInfo)
// 接收事件
this.$eventBus.$on('user-login', (userInfo) => {
console.log(userInfo)
})
3. Uniapp 自带的 globalData
在 App.vue
中定义:
export default {
globalData: {
userInfo: null
},
onLaunch() {
// 初始化
}
}
任何页面获取和修改:
// 获取
const app = getApp()
console.log(app.globalData.userInfo)
// 设置
app.globalData.userInfo = {name: 'John'}
4. Pinia(Vuex 的替代方案)
Pinia 是新一代的 Vue 状态管理库,更轻量且易于使用。
安装与配置
- 安装:
npm install pinia @pinia/nuxt
- 在
main.js
中:
import { createPinia } from 'pinia'
const pinia = createPinia()
const app = new Vue({
pinia,
...App
})
- 创建 store (
stores/user.js
):
import { defineStore } from 'pinia'
export const useUserStore = defineStore('user', {
state: () => ({
name: 'John',
age: 30
}),
actions: {
updateName(newName) {
this.name = newName
}
}
})
- 组件中使用:
import { useUserStore } from '@/stores/user'
export default {
setup() {
const userStore = useUserStore()
return {
userStore
}
}
}
选择建议
- 小型应用:使用 globalData 或事件总线
- 中型应用:使用 Vuex
- 新项目或喜欢新特性:考虑 Pinia
每种方案都有其适用场景,根据项目复杂度选择最合适的方案。