在 Vue 2 中使用 Vuex 的主要步骤包括安装 Vuex、创建 Vuex Store、在主应用中引入 Store 以及在组件中使用 Store。以下是一个详细的示例:
1. 安装 Vuex
首先,确保你的项目中已经安装了 Vuex。如果还没有安装,你可以通过 npm 或 yarn 来安装它:
npm install vuex@3 --save
# 或者
yarn add vuex@3
注意:Vue 2 不支持 Vuex 4.0 及其以上的版本,因此这里安装的是 Vuex 3.x 版本。
2. 创建 Vuex Store
在项目的 src 目录下创建一个名为 store 的文件夹,并在其中创建一个 index.js 文件来定义你的 Vuex store。
// src/store/index.js
import Vue from 'vue';
import Vuex from 'vuex';
Vue.use(Vuex);
export default new Vuex.Store({
state: {
count: 0 // 定义一个初始状态
},
mutations: {
increment(state) {
state.count++; // 定义一个同步函数来更改状态
},
decrement(state) {
state.count--;
}
},
actions: {
incrementAsync({ commit }) {
setTimeout(() => {
commit('increment'); // 定义一个异步操作,通过提交 mutation 来更改状态
}, 1000);
}
},
getters: {
doubleCount: state => state.count * 2 // 定义一个 getter 来计算新的值
}
});
3. 在主应用中引入 Store
在你的应用的入口文件(通常是 main.js)中,引入并使用刚创建的 store。
// src/main.js
import Vue from 'vue';
import App from './App.vue';
import store from './store';
new Vue({
store, // 注册 store
render: h => h(App)
}).$mount('#app');
4. 在组件中使用 Store
现在你可以在组件中使用 this.$store 来访问 Vuex store,并通过 mapState、mapGetters、mapActions、mapMutations 辅助函数来简化状态、getter、action、mutation 的访问和调用。
<template>
<div>
<p>Count: {{ count }}</p>
<p>Double Count: {{ doubleCount }}</p>
<button @click="increment">Increment</button>
<button @click="decrement">Decrement</button>
<button @click="incrementAsync">Increment Async</button>
</div>
</template>
<script>
import { mapState, mapGetters, mapActions } from 'vuex';
export default {
computed: {
...mapState(['count']), // 映射 state 中的 count
...mapGetters(['doubleCount']), // 映射 getter
},
methods: {
...mapActions(['increment', 'decrement', 'incrementAsync']), // 映射 actions
}
};
</script>
在这个例子中,我们创建了一个简单的计数器应用,展示了如何在 Vue 2 中使用 Vuex 管理状态。组件能够访问和修改 store 中的 count 状态,同时使用了异步 action 来模拟延迟的计数增加。




Comments NOTHING