1、安装 Vuex
可以通过 npm 或 yarn 来安装它
npm install vuex
yarn add vuex
2、创建 Vuex Store
在Vue 项目中,需要创建一个 Vuex store。这通常是一个单独的 JavaScript 文(如 store.js),位于项目的 src 目录下
// src/store.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++;
}
},
actions: {
increment({ commit }) {
commit('increment');
}
},
modules: {
// 可以在这里定义模块化的 state
}
});
3、在 Vue 应用中使用 Store
在 Vue 实例(通常是 main.js 或 main.ts)中,需要引入并使用这个 store。
// 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');
4、在组件中使用 Vuex
你可以在组件中通过 this.$store.state.count 访问 state 中的数据,通过this.$store.commit('increment')提交 mutation 来改变状态,或者通过 this.$store.dispatch('increment')派发 action
然而,直接在组件中访问 $store 并不是最佳实践,因为这会让你的组件和 Vuex 紧密耦合。为了解耦,你可以使用 mapState、mapMutations、mapActions 等辅助函数来映射 state、mutations 和 actions 到局部计算属性(computed)和方法(methods)中。
// 在组件中
import { mapState, mapMutations, mapActions } from 'vuex';
export default {
computed: {
...mapState(['count'])
},
methods: {
...mapMutations(['increment']),
...mapActions(['increment']),
incrementCount() {
// 可以使用 this.increment() 来调用 mutation
// 或者使用 this.increment() 来派发 action
this.increment();
}
}
};
5、模块化 Vuex Store
当你的项目变得复杂时,你可能需要将 Vuex store 分割成多个模块。在上面的 store.js 示例中,你可以看到 modules字段,你可以在这里定义你的模块。每个模块都有自己的 state、mutations、actions 和 getters。
6、使用 Getters
Getters 是 Vuex store 中的计算属性,它们允许你定义基于 state 的派生状态。你可以在 getters 中返回计算后的值,并在组件中通过 this.$store.getters.someGetter 来访问它们。同样,你也可以使用 mapGetters 辅助函数来映射 getters 到组件的 computed 属性中。