Vuex 基本使用,map方法的使用,模块化+命名空间

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'])

ps:仅作为个人学习记录,如有错误请指出,欢迎交流

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值