vue实现store
Vue 中实现 Store 的几种方法
在 Vue 中实现状态管理(Store)有多种方式,可以根据项目需求选择适合的方案。
使用 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
在 main.js 中注入 store:
import store from './store'
new Vue({
store,
// ...其他选项
})
使用 Composition API 实现简单 Store
对于小型项目,可以使用 Vue 3 的 Composition API 创建简单的 store:
import { reactive } from 'vue'
export const store = reactive({
state: {
count: 0
},
increment() {
this.state.count++
}
})
在组件中使用:
import { store } from './store'
export default {
setup() {
return {
store
}
}
}
使用 Pinia(Vuex 的替代方案)
Pinia 是 Vue 官方推荐的新一代状态管理库,更简单且类型安全。
安装 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
}
})
在 main.js 中设置:
import { createPinia } from 'pinia'
const pinia = createPinia()
app.use(pinia)
在组件中使用:
import { useCounterStore } from '@/stores/counter'
export default {
setup() {
const counter = useCounterStore()
return { counter }
}
}
使用 Provide/Inject 实现跨组件状态共享
对于简单的跨组件状态共享,可以使用 Vue 的 provide/inject:

// 父组件
export default {
provide() {
return {
sharedState: reactive({
count: 0
})
}
}
}
// 子组件
export default {
inject: ['sharedState']
}
选择哪种方案取决于项目规模和复杂度。小型项目可以使用 Composition API 或 provide/inject,中大型项目推荐使用 Pinia 或 Vuex。






