核心概念
1. State(状态):
Vuex 使用单一状态树,即用一个对象就包含了全部的应用层级状态。
在 Vuex 中定义的状态存储在 state 对象中,组件通过 this.$store.state.xxx 访问状态。
2. Getters(获取器):
Getters 允许组件从 store 中获取数据,类似于 Vue 实例中的计算属性。
可以通过 getters 对象的属性访问。
3. Mutations(突变):
Mutations 是唯一修改 store 中状态的方法,每个 mutation 都有一个字符串的事件类型(type)和一个回调函数。
提交 mutation 是更改状态的唯一方法,通过 commit 方法触发。
4. Actions(动作):
Actions 类似于 Mutations,但是它提交的是 mutation 而不是直接变更状态。
可以包含任意异步操作,通过 dispatch 方法触发。
5. Modules(模块):
Modules 允许将 store 分割成模块,每个模块拥有自己的 state、getters、mutations、actions
提供了更好的组织管理大型的 store 对象。
使用 Vuex 的步骤
1. 安装 Vuex
npm install vuex --save
2. 创建并配置 Vuex Store
在项目中创建一个 Vuex store 文件,通常命名为 store.js:
import Vue from 'vue';
import Vuex from 'vuex';
Vue.use(Vuex);
const state = {
count: 0
};
const getters = {
getCount: state => state.count
};
const mutations = {
increment(state) {
state.count++;
},
decrement(state) {
state.count--;
}
};
const actions = {
incrementAction({ commit }) {
commit('increment');
},
decrementAction({ commit }) {
commit('decrement');
}
};
export default new Vuex.Store({
state,
getters,
mutations,
actions
});
3. 在 Vue 应用中使用 Vuex
在 main.js 或者需要使用状态管理的地方引入 store 并将其配置到 Vue 实例中:
import Vue from 'vue';
import App from './App.vue';
import store from './store';
new Vue({
el: '#app',
store,
render: h => h(App)
});
4. 在组件中使用 Vuex
在组件中可以通过 this.$store 访问 store 中的 state、getters、mutations 和 actions。
<template>
<div>
<p>Count: {{ count }}</p>
<button @click="increment">Increment</button>
<button @click="decrement">Decrement</button>
</div>
</template>
<script>
export default {
computed: {
count() {
return this.$store.getters.getCount;
}
},
methods: {
increment() {
this.$store.dispatch('incrementAction');
},
decrement() {
this.$store.dispatch('decrementAction');
}
}
};
</script>
总结
Vuex 是 Vue.js 的官方状态管理库,它通过集中式存储管理应用的所有组件的状态,使用了一些核心概念如 state、getters、mutations 和 actions 来实现状态管理。使用 Vuex 可以帮助应用更加清晰和易于维护,尤其适用于大型单页应用的状态管理。