简单vue状态管理实现
Vue 状态管理实现方法
使用 Vue 的响应式系统
Vue 的响应式系统可以轻松实现简单的状态管理。通过创建一个响应式对象,可以在多个组件之间共享状态。
// store.js
import { reactive } from 'vue';
export const store = reactive({
count: 0,
increment() {
this.count++;
}
});
在组件中使用:
import { store } from './store';
export default {
setup() {
return { store };
}
};
使用 provide/inject
对于跨层级组件共享状态,可以使用 provide 和 inject。在父组件中提供状态,在子组件中注入使用。
// 父组件
import { provide, reactive } from 'vue';
export default {
setup() {
const state = reactive({ count: 0 });
provide('state', state);
return { state };
}
};
// 子组件
import { inject } from 'vue';
export default {
setup() {
const state = inject('state');
return { state };
}
};
使用 Vuex 的轻量级替代方案
对于需要更复杂状态管理的场景,可以创建一个类似 Vuex 的轻量级解决方案。
// store.js
import { reactive } from 'vue';
export const store = reactive({
state: {
count: 0
},
mutations: {
increment(state) {
state.count++;
}
}
});
在组件中使用:
import { store } from './store';
export default {
setup() {
const increment = () => store.mutations.increment(store.state);
return { count: store.state.count, increment };
}
};
使用 Pinia
Pinia 是 Vue 的官方推荐状态管理库,比 Vuex 更简单且类型安全。
// stores/counter.js
import { defineStore } from 'pinia';
export const useCounterStore = defineStore('counter', {
state: () => ({ count: 0 }),
actions: {
increment() {
this.count++;
}
}
});
在组件中使用:
import { useCounterStore } from '@/stores/counter';
export default {
setup() {
const counter = useCounterStore();
return { counter };
}
};
这些方法可以根据项目需求选择使用,从简单的响应式对象到更复杂的状态管理方案都能满足不同场景的需求。







