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
在组件中使用:
import { mapState, mapActions, mapGetters } from 'vuex'
export default {
computed: {
...mapState(['count']),
...mapGetters(['doubleCount'])
},
methods: {
...mapActions(['increment'])
}
}
使用 Pinia
Pinia 是 Vue 的轻量级状态管理库,提供更简单的 API 和更好的 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'
export default {
setup() {
const counter = useCounterStore()
return { counter }
}
}
使用 Composition API
对于小型应用,可以直接使用 Vue 3 的 Composition API 实现简单状态管理。
创建响应式状态:
import { reactive } from 'vue'
const state = reactive({
count: 0
})
export function useCounter() {
const increment = () => {
state.count++
}
const doubleCount = () => state.count * 2
return {
state,
increment,
doubleCount
}
}
在组件中使用:
import { useCounter } from '@/composables/counter'
export default {
setup() {
const { state, increment, doubleCount } = useCounter()
return { state, increment, doubleCount }
}
}
使用 Provide/Inject
对于组件层级较深的状态共享,可以使用 provide/inject 实现。
提供状态:

import { provide, reactive } from 'vue'
export default {
setup() {
const state = reactive({
count: 0
})
const increment = () => {
state.count++
}
provide('counter', { state, increment })
}
}
注入状态:
import { inject } from 'vue'
export default {
setup() {
const { state, increment } = inject('counter')
return { state, increment }
}
}
使用 Event Bus
对于简单应用,可以使用事件总线实现跨组件通信。
创建事件总线:
import Vue from 'vue'
export const EventBus = new Vue()
发送事件:
EventBus.$emit('increment', 1)
接收事件:
EventBus.$on('increment', (amount) => {
this.count += amount
})






