1. 创建 Vue 2 项目
如果你还没有安装 Vue CLI,可以使用以下命令进行全局安装:
npm install -g @vue/cli
接着创建一个新的 Vue 2 项目:
vue create my-vue2-app --default
cd my-vue2-app
2. 安装 Vuex
在项目根目录下,通过以下命令安装 Vuex:
npm install vuex --save
3. 创建 Vuex 存储(Store)
在src目录下创建一个store文件夹,并在其中创建一个index.js文件,用于定义和配置 Vuex 存储。
javascript
// src/store/index.js
import Vue from 'vue';
import Vuex from 'vuex';
// 使用 Vuex 插件
Vue.use(Vuex);
// 创建一个新的 store 实例
const store = new Vuex.Store({
// 状态(state)是存储应用数据的地方
state: {
count: 0
},
// mutations 用于修改 state,必须是同步函数
mutations: {
increment(state) {
state.count++;
},
decrement(state) {
state.count--;
}
},
// actions 用于处理异步操作,最终会触发 mutations
actions: {
incrementAsync(context) {
setTimeout(() => {
context.commit('increment');
}, 1000);
}
},
// getters 类似于计算属性,用于获取 state 中的数据
getters: {
doubleCount(state) {
return state.count * 2;
}
}
});
export default store;
4. 在 Vue 2 应用中使用 Vuex 存储
在main.js文件中导入并使用 Vuex 存储。
javascript
// src/main.js
import Vue from 'vue';
import App from './App.vue';
import store from './store';
new Vue({
store,
render: h => h(App)
}).$mount('#app');
5. 在组件中使用 Vuex
在组件中可以使用不同的方式来访问和修改 Vuex 存储中的数据。
5.1 使用mapState、mapMutations、mapActions和mapGetters辅助函数
<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, mapMutations, mapActions, mapGetters } from 'vuex';
export default {
computed: {
// 使用 mapState 获取 state 中的数据
...mapState(['count']),
// 使用 mapGetters 获取 getters 中的数据
...mapGetters(['doubleCount'])
},
methods: {
// 使用 mapMutations 触发 mutations
...mapMutations(['increment', 'decrement']),
// 使用 mapActions 触发 actions
...mapActions(['incrementAsync'])
}
};
</script>
5.2 直接访问this.$store
<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>
export default {
computed: {
// 直接从 $store 中获取 state 数据
count() {
return this.$store.state.count;
},
// 直接从 $store 中获取 getters 数据
doubleCount() {
return this.$store.getters.doubleCount;
}
},
methods: {
// 直接使用 $store.commit 触发 mutations
increment() {
this.$store.commit('increment');
},
decrement() {
this.$store.commit('decrement');
},
// 直接使用 $store.dispatch 触发 actions
incrementAsync() {
this.$store.dispatch('incrementAsync');
}
}
};
</script>
总结
通过以上步骤,你可以在 Vue 2 项目中成功使用 Vuex 来管理应用的状态。在组件中,可以使用辅助函数或直接访问this.$store来获取和修改 Vuex 存储中的数据。