1. 初始化数据
/** 引入Vue核心库 */
import Vue from "vue";
/** 引入Vuex */
import Vuex from "vuex";
/** 使用Vuex */
Vue.use(Vuex);
/** 初始化数据 */
const state = {
sum: 0,
};
/** 对state中的数据进行加工 */
const getters = {
bigSum(state) {
return state.sum * 10;
},
};
/** 响应组件中的动作 */
const actions = {
add(context, value) {
context.commit("ADD", value);
},
};
/** 用于操作数据 */
const mutations = {
ADD(state, value) {
state.sum += value;
},
};
/** 创建并暴露store */
export default new Vuex.store({
state,
getters,
actions,
mutations,
});
2. 组建中读取Vuex中的数据
$store.state.sum
3. 组件中修改vuex中的数据
$store.dispath("action中的方法名", '数据') 或
$store.commit('mutations中的方法名','数据')
// 若没有网络请求或其他业务逻辑,组件中可以越过actions,即不写dispatch,直接编写commit
4. getter的使用
$store.getters.bigSum
5. mapState与mapGetter的使用
mapState:用于映射state中的数据为计算属性
mapGetters:映射getters中的数据为计算属性
import { mapState, mapGetters } from "vuex";
export default {
computed: {
...mapState(["sum"]),
...mapGetters(["bigSum"]),
},
};
6. mapActions与mapMutations的使用
mapActions:用于帮助映射actions对话方法,即包含this.$store.dispatch(xxx)的函数
mapMutations:用于帮助映射mutations对话方法,即包含this.$store.commit(xxx)的函数
import { mapMutations, mapActions } from "vuex";
export default {
methods: {
...mapMutations['add'],
...mapMutations['ADD']
},
};
注:使用mapMutations,mapActions时若需要传递参数,则在模板中绑定事件时传递好参数,否则参数将是事件对象
7. 模块化+命名空间
const countAbout = {
namespaced: true, // 命名空间开启
state: { a: "1" },
mutations: { ... },
actions: { ... },
getters: {
bigSum(state) {
return state.sum * 10;
},
},
};
const personAbout = {
namespaced: true,
state: { b: 1 },
mutations: {
ADD(state, value) {
state.sum += value;
},
},
actions: {
add(context, value) {
context.commit("ADD", value);
},
},
};
const store = new Vuex.store({
modules: {
countAbout,
personAbout,
},
});
/** 开启命名空间后,组件中读取state数据 */
直接读取:this.$store.state.presonAbout.b
借助mapState读取:...mapState('countAbout',['b'])
/** 开启命名空间后,组件中读取getters数据 */
直接读取:this.$store.getters['countAbout/bigSum']
借助mapGetters读取:...mapGetters('countAbout',['bigSum'])
/** 开启命名空间后,组件中调用dispatch */
直接调用:this.$store.dispatch('personAbout/add',xxx)
借助mapActions:...mapActions('personAbout',['add'])
/** 开启命名空间后,组件中调用commit */
直接调用:this.$store.commit('personAbout/ADD',xxx)
借助mapMutations('personAbout',['ADD'])