vue实现store
Vue 实现 Store
在 Vue 中,可以通过 Vuex 或 Pinia 实现全局状态管理(Store)。以下是两种主流方案的实现方法。
使用 Vuex 实现 Store
Vuex 是 Vue 的官方状态管理库,适合中大型项目。
安装 Vuex
npm install vuex --save
创建 Store
// store/index.js
import { createStore } from 'vuex';
export default createStore({
state: {
count: 0
},
mutations: {
increment(state) {
state.count++;
}
},
actions: {
incrementAsync({ commit }) {
setTimeout(() => {
commit('increment');
}, 1000);
}
},
getters: {
doubleCount(state) {
return state.count * 2;
}
}
});
在 Vue 中注入 Store

// main.js
import { createApp } from 'vue';
import App from './App.vue';
import store from './store';
const app = createApp(App);
app.use(store);
app.mount('#app');
组件中使用 Store
<template>
<div>
<p>Count: {{ $store.state.count }}</p>
<p>Double: {{ $store.getters.doubleCount }}</p>
<button @click="$store.commit('increment')">Increment</button>
<button @click="$store.dispatch('incrementAsync')">Async Increment</button>
</div>
</template>
使用 Pinia 实现 Store
Pinia 是 Vue 的轻量级状态管理库,推荐用于新项目。
安装 Pinia

npm install pinia
创建 Store
// stores/counter.js
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
}
});
在 Vue 中注入 Pinia
// main.js
import { createApp } from 'vue';
import { createPinia } from 'pinia';
import App from './App.vue';
const app = createApp(App);
app.use(createPinia());
app.mount('#app');
组件中使用 Store
<template>
<div>
<p>Count: {{ counter.count }}</p>
<p>Double: {{ counter.doubleCount }}</p>
<button @click="counter.increment()">Increment</button>
<button @click="counter.incrementAsync()">Async Increment</button>
</div>
</template>
<script setup>
import { useCounterStore } from '@/stores/counter';
const counter = useCounterStore();
</script>
选择建议
- Vuex:适合需要严格状态管理的中大型项目,支持模块化和插件。
- Pinia:更轻量、易用,支持 TypeScript 和 Composition API,推荐新项目使用。
两种方案均能实现全局状态管理,根据项目需求选择即可。






