vue实现简单的store
Vue 实现简单 Store
在 Vue 中实现一个简单的 Store 可以通过多种方式完成,以下是几种常见的方法:
使用 Vue 的响应式系统
通过 Vue 的 reactive 或 ref 创建一个响应式对象作为 Store:
import { reactive } from 'vue';
const store = reactive({
state: {
count: 0
},
increment() {
this.state.count++;
}
});
export default store;
在组件中使用:
import store from './store';
export default {
setup() {
return {
store
};
}
};
使用 Vuex 的简化版本
Vuex 是 Vue 的官方状态管理库,但可以手动实现一个简化版本:

import { reactive } from 'vue';
const createStore = () => {
const state = reactive({
count: 0
});
const mutations = {
increment(state) {
state.count++;
}
};
return {
state,
commit(mutationName) {
mutations[mutationName](state);
}
};
};
export const store = createStore();
在组件中使用:
import { store } from './store';
export default {
setup() {
return {
store
};
}
};
使用 Provide/Inject
通过 Vue 的 provide 和 inject 实现全局状态共享:

import { provide, reactive } from 'vue';
const store = reactive({
count: 0,
increment() {
this.count++;
}
});
export const useStore = () => {
provide('store', store);
return store;
};
在子组件中使用:
import { inject } from 'vue';
export default {
setup() {
const store = inject('store');
return {
store
};
}
};
使用 Pinia 的简化版本
Pinia 是 Vue 的轻量级状态管理库,可以手动实现类似功能:
import { reactive } from 'vue';
const useStore = () => {
const state = reactive({
count: 0
});
function increment() {
state.count++;
}
return {
state,
increment
};
};
export default useStore;
在组件中使用:
import useStore from './store';
export default {
setup() {
const store = useStore();
return {
store
};
}
};
选择建议
- 对于小型应用,使用
reactive或provide/inject足够。 - 需要更严格的状态管理时,可以考虑手动实现类似 Vuex 或 Pinia 的简化版本。
- 对于大型应用,直接使用 Vuex 或 Pinia 更合适。






