简介
Vuex是一个专为Vue.js应用程序开发的状态管理模式。它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态的一致性。
核心
Vuex的核心包括state、mutations、actions和getters。
-
state: Vuex中的状态存储。可以将它看作是应用程序的单一数据源,类似于Vue实例的data对象。
-
mutations: Vuex中的状态修改。mutations是唯一允许修改state的地方,每个mutation都有一个字符串类型的事件类型和一个回调函数,用于对state进行修改。
-
actions: Vuex中的异步操作。actions可以包含任意异步操作,通过提交mutation来间接修改state。
-
getters: Vuex中的派生状态。getters可以通过对state的计算和处理返回一个新的状态,类似于Vue的计算属性。
安装
安装Vuex:可以通过npm、yarn或者CDN等方式安装Vuex。
npm i vuex --save
yarn add vuex
使用
在src目录下创建store文件夹:在store下新建index.js后续引入到main.js内。
注:vuex推荐使用模块化方式,尽量避免全部放在index.js内,存在命名问题,模块化的文件需添加 namespaced: true 开启命名空间。
命名空间:Vuex 的命名空间是一种将模块化的状态和操作方法进行隔离的机制。通过使用命名空间,可以在多个模块中定义相同的 state、getters、mutations、actions 等,而不会发生命名冲突。同时,在组件中调用模块中的状态和操作方法时,也需要加上命名空间前缀。
import Vue from "vue";
import Vuex from "vuex";
import user from "./modules/user";
import getters from "./getters";
Vue.use(Vuex);
const store = new Vuex.Store({
modules: {
user,
},
getters,
});
export default store;
全局挂载
import Vue from "vue";
import App from "./App.vue";
import store from "./store";
Vue.config.productionTip = false;
Vue.prototype.$store = store;
new Vue({
store,
render: (h) => h(App),
}).$mount("#app");
组件内使用 (常规方式)
// 组件中使用
export default {
computed: {
count() {
return this.$store.state.dataNmae
},
doubleCount() {
return this.$store.getters.dataNmae
}
},
methods: {
increment() {
this.$store.commit('mutations')
},
incrementAsync() {
this.$store.dispatch('actions')
}
}
}
组件内使用(辅助函数方式)
在组件中访问命名空间模块的状态和操作方法时,需要使用 mapState
、mapGetters
、mapMutations
、mapActions
等辅助函数时,也需要指定命名空间前缀。
import { mapGetters, createNamespacedHelpers } from "vuex";
const { mapMutations, mapState, mapActions } = createNamespacedHelpers("user");
export default {
components: {},
data() {
return {};
},
computed: {
...mapGetters(["name"]),
...mapState({
stateName: (state) => state.name,
}),
},
created() {},
methods: {
...mapActions(["Actions"]),
...mapMutations(["Mutations"]),
handleChangeName() {
this.$store.commit("user/Mutations", "data");
},
handleChangeNameHelp() {
this.Mutations("data");
},
handleChangeNameAsyc() {
this.$store.dispatch("user/Actions", "data");
},
handleChangeNameHelpAsyc() {
this.Actions("data");
},
},
辅助函数与原型在dom上使用的区别
<div>原型写法:{{ $store.state.user.name }}</div>
<div>mapStates写法:{{ stateName }}</div>