vue实现简单的store
Vue 实现简单的 Store
在 Vue 中可以通过多种方式实现简单的状态管理(Store),以下介绍几种常见方法:
使用 Vue 的响应式 API
通过 reactive 或 ref 创建响应式对象,实现一个轻量级 Store:
import { reactive } from 'vue';
// 创建 store
const store = reactive({
count: 0,
increment() {
this.count++;
}
});
// 在组件中使用
export default {
setup() {
return { store };
}
}
使用 provide/inject 跨组件共享
适合小型应用或组件层级较深的场景:
// 父组件提供 store
import { provide, reactive } from 'vue';
const store = reactive({ count: 0 });
provide('store', store);
// 子组件注入使用
import { inject } from 'vue';
const store = inject('store');
基于 Vuex 的简化实现
如果需要更结构化的状态管理,可以模仿 Vuex 的简化模式:
import { reactive } from 'vue';
function createStore() {
const state = reactive({
count: 0
});
const mutations = {
increment(state) {
state.count++;
}
};
return {
state,
commit(mutation) {
mutations[mutation](state);
}
};
}
export const store = createStore();
使用 Pinia(推荐)
对于现代 Vue 3 项目,Pinia 是官方推荐的状态管理方案:
// store/counter.js
import { defineStore } from 'pinia';
export const useCounterStore = defineStore('counter', {
state: () => ({
count: 0
}),
actions: {
increment() {
this.count++;
}
}
});
// 组件中使用
import { useCounterStore } from './stores/counter';
const counter = useCounterStore();
counter.increment();
每种方法适用于不同场景,小型项目可使用响应式 API 或 provide/inject,中大型项目推荐使用 Pinia。







