js实现vuex
Vuex 的基本概念
Vuex 是 Vue.js 的官方状态管理库,用于集中管理应用的状态。它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化。
使用 Vuex 的基本步骤
安装 Vuex 库:
npm install vuex --save
在项目中引入并使用 Vuex:
import Vue from 'vue';
import Vuex from 'vuex';
Vue.use(Vuex);
创建 Store
Store 是 Vuex 的核心,用于存储应用的状态。以下是创建 Store 的基本结构:
const store = new Vuex.Store({
state: {
count: 0
},
mutations: {
increment(state) {
state.count++;
}
},
actions: {
increment({ commit }) {
commit('increment');
}
},
getters: {
doubleCount: state => state.count * 2
}
});
State
State 是存储应用状态的地方,类似于组件的 data 属性。可以通过 this.$store.state 访问:
console.log(store.state.count); // 输出 0
Mutations
Mutations 是唯一可以修改 state 的方法。每个 mutation 都有一个字符串类型的事件类型和一个回调函数:

mutations: {
increment(state) {
state.count++;
}
}
调用 mutation:
store.commit('increment');
Actions
Actions 类似于 mutations,但可以包含异步操作。Actions 通过提交 mutations 来修改 state:
actions: {
incrementAsync({ commit }) {
setTimeout(() => {
commit('increment');
}, 1000);
}
}
调用 action:
store.dispatch('incrementAsync');
Getters
Getters 用于从 state 中派生出一些状态,类似于组件的计算属性:

getters: {
doubleCount: state => state.count * 2
}
访问 getter:
console.log(store.getters.doubleCount); // 输出 2(假设 count 为 1)
在 Vue 组件中使用 Vuex
在 Vue 组件中,可以通过 this.$store 访问 store 的 state、mutations、actions 和 getters:
export default {
computed: {
count() {
return this.$store.state.count;
},
doubleCount() {
return this.$store.getters.doubleCount;
}
},
methods: {
increment() {
this.$store.commit('increment');
},
incrementAsync() {
this.$store.dispatch('incrementAsync');
}
}
};
模块化 Vuex
对于大型应用,可以将 store 分割成模块(modules)。每个模块拥有自己的 state、mutations、actions 和 getters:
const moduleA = {
state: { ... },
mutations: { ... },
actions: { ... },
getters: { ... }
};
const moduleB = {
state: { ... },
mutations: { ... },
actions: { ... },
getters: { ... }
};
const store = new Vuex.Store({
modules: {
a: moduleA,
b: moduleB
}
});
访问模块中的 state:
store.state.a; // 访问 moduleA 的状态
store.state.b; // 访问 moduleB 的状态
总结
Vuex 提供了一种集中式管理应用状态的方式,通过 state、mutations、actions 和 getters 的组合,可以更好地管理和维护大型应用的状态。模块化的设计使得代码结构更加清晰,便于维护和扩展。






