VueX 安装教程
本文将指导你完成 VueX 的安装和基本配置,帮助你快速搭建一个包含状态管理的 Vue.js 项目。
准备工作
在开始之前,请确保你已经安装了以下依赖:
- Node.js 和 npm(或 yarn)
- Vue.js(建议版本 2.6.0 或更高)
创建 Vue 项目
使用 Vue CLI 创建一个新的 Vue 项目,如果尚未安装 Vue CLI,请先执行以下命令:
npm install -g @vue/cli

然后创建一个新的项目:
vue create my-vue-app
在创建过程中,你可以选择默认配置或手动选择特性,确保勾选 VueX。
安装 VueX
如果你没有在创建项目时选择 VueX,可以在项目根目录下手动安装:
npm install vuex
配置 VueX
创建 Store 文件
在项目根目录下创建一个名为 `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');
}
},
getters: {
count: state => state.count
}
});
在 VueX 项目中引入 Store
在 `main.js` 文件中引入并使用 Store:
import Vue from 'vue';
import App from './App.vue';
import store from './store';
new Vue({
store,
render: h => h(App)
}).$mount('#app');
在组件中使用 Store
获取状态
在任何组件中,你可以通过 `this.$store.state` 访问状态:
export default {
template: `
{{ count }}
`,
computed: {
count() {
return this.$store.state.count;
}
}
};
提交 Mutation
通过 `this.$store.commit` 提交 Mutation:
export default {
methods: {
increment() {
this.$store.commit('increment');
}
}
};
分发 Action
通过 `this.$store.dispatch` 分发 Action:
export default {
methods: {
increment() {
this.$store.dispatch('increment');
}
}
};
高级配置
模块化 Store
对于大型项目,建议将 Store 模块化:
import Vue from 'vue';
import Vuex from 'vuex';
Vue.use(Vuex);
const moduleA = {
state: () => ({
count: 0
}),
mutations: {
increment(state) {
state.count++;
}
}
};
const moduleB = {
// ...
};
export default new Vuex.Store({
modules: {
a: moduleA,
b: moduleB
}
});
持久化 Store
可以使用插件如 `vuex-persistedstate` 来持久化 Store 状态:
npm install vuex-persistedstate
然后在 Store 中配置:
import createPersistedState from 'vuex-persistedstate';
const store = new Vuex.Store({
// ...
});
store.use(createPersistedState());