vue 状态管理实现
Vue 状态管理实现方法
Vue 的状态管理可以通过多种方式实现,以下是常见的几种方法:
使用 Vuex
Vuex 是 Vue 官方推荐的状态管理库,适用于中大型应用。它采用集中式存储管理应用的所有组件的状态。
安装 Vuex:
npm install vuex --save
创建 store:
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const store = new Vuex.Store({
state: {
count: 0
},
mutations: {
increment (state) {
state.count++
}
},
actions: {
increment ({ commit }) {
commit('increment')
}
},
getters: {
doubleCount: state => state.count * 2
}
})
export default store
在组件中使用:
// 获取状态
this.$store.state.count
// 提交 mutation
this.$store.commit('increment')
// 分发 action
this.$store.dispatch('increment')
// 获取 getter
this.$store.getters.doubleCount
使用 Pinia
Pinia 是 Vue 官方推荐的下一代状态管理库,比 Vuex 更简单且支持 TypeScript。
安装 Pinia:
npm install pinia
创建 store:
import { defineStore } from 'pinia'
export const useCounterStore = defineStore('counter', {
state: () => ({
count: 0
}),
actions: {
increment() {
this.count++
}
},
getters: {
doubleCount: (state) => state.count * 2
}
})
在组件中使用:
import { useCounterStore } from '@/stores/counter'
const counter = useCounterStore()
// 获取状态
counter.count
// 调用 action
counter.increment()
// 获取 getter
counter.doubleCount
使用 Composition API
对于小型应用,可以直接使用 Vue 3 的 Composition API 实现简单的状态管理。
创建响应式状态:
// store.js
import { reactive } from 'vue'
export const store = reactive({
count: 0,
increment() {
this.count++
}
})
在组件中使用:
import { store } from './store'
// 获取状态
store.count
// 修改状态
store.increment()
使用 Provide/Inject
Vue 的 provide/inject API 可以实现跨组件状态共享。
提供状态:
// App.vue
import { provide, reactive } from 'vue'
const state = reactive({
count: 0
})
provide('store', state)
注入状态:
// ChildComponent.vue
import { inject } from 'vue'
const store = inject('store')
// 使用状态
store.count++
使用 Event Bus
虽然不推荐用于大型应用,但 Event Bus 可以实现简单的组件间通信。
创建 Event Bus:
// eventBus.js
import Vue from 'vue'
export const EventBus = new Vue()
发送事件:
EventBus.$emit('event-name', payload)
接收事件:
EventBus.$on('event-name', (payload) => {
// 处理事件
})
选择建议
- 小型应用:Composition API 或 Provide/Inject
- 中型应用:Pinia
- 大型复杂应用:Vuex 或 Pinia
- 需要 TypeScript 支持:优先选择 Pinia
每种方法都有其适用场景,应根据项目规模和复杂度选择最合适的方案。







