Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式 + 库。它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化。
1、vuex 的核心概念:
- state:存储状态数据的地方,它是一个简单的 JavaScript 对象。
- getters:类似于计算属性,用于从 state 中派生出一些状态。
- mutations:用于变更 state 的唯一方式,它们必须是同步函数。
- actions:用于处理异步操作,可以包含任意数量的 mutations,并且可以触发多个mutations。
- modules:将 store 分割成多个模块,每个模块拥有自己的 state、getters、mutations 和 actions。
2、vuex 的使用:
安装 Vuex
首先,确保你的 Vue 项目中已经安装了 Vuex。如果还未安装,可以通过 npm 或 yarn 来安装:
npm安装
npm install vuex --save
yarn安装
yarn add vuex
创建 Vuex Store
创建一个名为 store.js
的文件,并配置 Vuex Store:
// store.js
import Vue from 'vue';
import Vuex from 'vuex';
Vue.use(Vuex);
export default new Vuex.Store({
state: {
count: 0 // 例子中的状态,用于计数
},
getters: {
getCount: state => state.count // 获取状态的方法
},
mutations: {
increment(state) { // 更改状态的方法
state.count++;
}
},
actions: {
incrementAsync({ commit }) { // 异步操作,提交 mutation
setTimeout(() => {
commit('increment');
}, 1000);
}
}
});
在 Vue 应用中使用 Vuex Store
接下来,在你的主要 Vue 实例或组件中使用这个 Store:
// main.js 或者在你想要使用 Vuex 的组件中
import Vue from 'vue';
import App from './App.vue';
import store from './store'; // 引入刚才创建的 store
new Vue({
el: '#app',
render: h => h(App),
store // 将 store 挂载到 Vue 实例上
});
// 在组件中使用 Vuex
export default {
computed: {
count() { // 访问状态
return this.$store.getters.getCount;
}
},
methods: {
increment() { // 提交 mutation
this.$store.commit('increment');
},
incrementAsync() { // 调用 action
this.$store.dispatch('incrementAsync');
}
}
};
以上示例展示了如何设置一个简单的 Vuex Store 来管理状态,并在 Vue 组件中访问和修改这些状态。通过这种方式,你可以更高效地管理跨组件共享的状态,并确保状态变更的可追踪性和一致性。
相关链接文章 👉 Vuex 是什么? | Vuex