vue实现store
Vue 中实现 Store 的方法
在 Vue 中,可以通过多种方式实现状态管理(Store),以下是常见的几种方法:
使用 Vuex
Vuex 是 Vue 的官方状态管理库,适用于中大型应用。
-
安装 Vuex:
npm install vuex -
创建 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 => state.count * 2 } }) -
在 main.js 中引入 Store:
import store from './store' new Vue({ store, render: h => h(App) }).$mount('#app') -
在组件中使用:
this.$store.commit('increment') // 调用 mutation this.$store.dispatch('increment') // 调用 action this.$store.state.count // 访问 state this.$store.getters.doubleCount // 访问 getter
使用 Pinia
Pinia 是 Vue 的下一代状态管理库,更轻量且类型安全。
-
安装 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 中引入 Pinia:
import { createPinia } from 'pinia' const pinia = createPinia() new Vue({ pinia, render: h => h(App) }).$mount('#app') -
在组件中使用:
import { useCounterStore } from '@/stores/counter' export default { setup() { const counter = useCounterStore() return { counter } } }
使用 Composition API 实现简易 Store
对于小型应用,可以直接使用 Vue 的 Composition API 实现简易 Store。
-
创建 Store 文件(如
store/counter.js):import { reactive } from 'vue' const state = reactive({ count: 0 }) export function useCounterStore() { function increment() { state.count++ } return { state, increment } } -
在组件中使用:
import { useCounterStore } from '@/store/counter' export default { setup() { const { state, increment } = useCounterStore() return { state, increment } } }
使用 provide/inject 实现全局状态
适用于需要在多个组件间共享状态的场景。
-
在根组件中提供状态:
import { provide, reactive } from 'vue' export default { setup() { const state = reactive({ count: 0 }) function increment() { state.count++ } provide('counter', { state, increment }) } } -
在子组件中注入状态:
import { inject } from 'vue' export default { setup() { const { state, increment } = inject('counter') return { state, increment } } }
选择建议
- 小型应用:使用 Composition API 或 provide/inject
- 中型应用:使用 Pinia
- 大型应用或需要迁移的项目:使用 Vuex
每种方法都有其适用场景,根据项目需求选择最合适的方案。







