vue model store 实现
Vue 状态管理实现方案
Vue 的状态管理可以通过多种方式实现,包括 Vuex、Pinia 或 Composition API 提供的响应式状态。以下是几种常见的实现方法。
使用 Vuex 实现状态管理
Vuex 是 Vue 的官方状态管理库,适合中大型应用。安装 Vuex 后,可以创建 store 并定义 state、mutations、actions 和 getters。
import { createStore } from 'vuex';
const store = createStore({
state() {
return {
count: 0
};
},
mutations: {
increment(state) {
state.count++;
}
},
actions: {
incrementAsync({ commit }) {
setTimeout(() => {
commit('increment');
}, 1000);
}
},
getters: {
doubleCount(state) {
return state.count * 2;
}
}
});
export default store;
在组件中使用 Vuex store:
import { useStore } from 'vuex';
export default {
setup() {
const store = useStore();
return {
count: computed(() => store.state.count),
doubleCount: computed(() => store.getters.doubleCount),
increment: () => store.commit('increment'),
incrementAsync: () => store.dispatch('incrementAsync')
};
}
};
使用 Pinia 实现状态管理
Pinia 是 Vue 的轻量级状态管理库,更适合现代 Vue 3 应用。Pinia 的 API 更简洁,支持 TypeScript。
import { defineStore } from 'pinia';
export const useCounterStore = defineStore('counter', {
state: () => ({
count: 0
}),
actions: {
increment() {
this.count++;
},
async incrementAsync() {
setTimeout(() => {
this.increment();
}, 1000);
}
},
getters: {
doubleCount: (state) => state.count * 2
}
});
在组件中使用 Pinia store:
import { useCounterStore } from '@/stores/counter';
export default {
setup() {
const counter = useCounterStore();
return {
count: computed(() => counter.count),
doubleCount: computed(() => counter.doubleCount),
increment: () => counter.increment(),
incrementAsync: () => counter.incrementAsync()
};
}
};
使用 Composition API 实现简单状态管理
对于小型应用,可以直接使用 Vue 3 的 Composition API 和 reactive 或 ref 实现状态管理。
import { reactive, readonly } from 'vue';
const state = reactive({
count: 0
});
const mutations = {
increment() {
state.count++;
}
};
const actions = {
incrementAsync() {
setTimeout(() => {
mutations.increment();
}, 1000);
}
};
const getters = {
doubleCount() {
return state.count * 2;
}
};
export const useStore = () => {
return {
state: readonly(state),
...mutations,
...actions,
...getters
};
};
在组件中使用自定义 store:
import { useStore } from '@/stores/counter';
export default {
setup() {
const store = useStore();
return {
count: computed(() => store.state.count),
doubleCount: computed(() => store.doubleCount()),
increment: store.increment,
incrementAsync: store.incrementAsync
};
}
};
选择合适的状态管理方案
- Vuex:适合需要严格状态管理的中大型项目,但 API 较复杂。
- Pinia:推荐用于 Vue 3 项目,API 更简洁,支持 TypeScript。
- Composition API:适合小型应用或简单状态管理需求,无需额外依赖。
根据项目规模和需求选择合适的状态管理方案。







