vue实现store
Vue 实现 Store 的方法
Vue 中实现 Store 通常用于状态管理,以下是几种常见的方法:
使用 Vuex
Vuex 是 Vue 官方推荐的状态管理库,适用于大型应用。
-
安装 Vuex:
npm install vuex --save -
创建 Store 文件(如
store/index.js):import Vue from 'vue' import Vuex from 'vuex' Vue.use(Vuex) export default new Vuex.Store({ state: { count: 0 }, mutations: { increment(state) { state.count++ } }, actions: { increment({ commit }) { commit('increment') } }, getters: { doubleCount(state) { return state.count * 2 } } }) -
在
main.js中引入 Store:import store from './store' new Vue({ store, render: h => h(App) }).$mount('#app') -
在组件中使用:
this.$store.state.count this.$store.commit('increment') this.$store.dispatch('increment') this.$store.getters.doubleCount
使用 Composition API 实现简易 Store
对于小型应用,可以直接使用 Vue 3 的 Composition API 实现简易 Store。
-
创建
store.js:
import { reactive } from 'vue' export const store = reactive({ count: 0, increment() { this.count++ } }) -
在组件中使用:
import { store } from './store' export default { setup() { return { store } } }
使用 Pinia
Pinia 是 Vue 官方推荐的下一代状态管理库,比 Vuex 更简洁。
-
安装 Pinia:
npm install pinia -
创建 Store(如
stores/counter.js):import { defineStore } from 'pinia' export const useCounterStore = defineStore('counter', { state: () => ({ count: 0 }), actions: { increment() { this.count++ } }, getters: { doubleCount: (state) => state.count * 2 } }) -
在
main.js中引入:
import { createPinia } from 'pinia' const pinia = createPinia() app.use(pinia) -
在组件中使用:
import { useCounterStore } from '@/stores/counter' const counter = useCounterStore() counter.count counter.increment() counter.doubleCount
使用 provide/inject 实现全局状态
适用于需要跨组件共享状态的场景。
-
创建全局状态:
import { reactive, provide, inject } from 'vue' const stateSymbol = Symbol('state') export const provideState = () => { const state = reactive({ count: 0, increment() { state.count++ } }) provide(stateSymbol, state) } export const useState = () => { const state = inject(stateSymbol) if (!state) throw new Error('State not provided') return state } -
在根组件提供状态:
import { provideState } from './state' export default { setup() { provideState() } } -
在子组件中使用:
import { useState } from './state' export default { setup() { const state = useState() return { state } } }
选择建议
- 大型应用:推荐使用 Vuex 或 Pinia
- 小型应用:Composition API 或 provide/inject
- 新项目:优先考虑 Pinia






