基于vuex 的全局组件通信(2021-5-25)

store/index.js

import Vue from "vue";
import Vuex from "vuex";
import testModule from "./modules/test";

Vue.use(Vuex);

export default new Vuex.Store({
  state: {
    user: {
      name: "",
      other: undefined
    },
    test: {
      testInfo: ""
    },
    conter: {
      num: 0
    }
  },
  getters: {
    conterAdd: state => addNum => {
      return state.conter.num + 10 + addNum;
    }
  },
  mutations: {
    increment(state, payload) {
      state.conter.num += payload;
    }
  },
  actions: {
    incrementAsync(context, num) {
      setTimeout(() => {
        context.commit("increment", num);
      }, 2000);
    }
  },
  modules: {
    test: testModule
  }
});

store/modules/test.js

const testModule = {
  namespaced: true, // 隔绝
  state: () => ({
    count: 0
  }),
  mutations: {
    increment(state) {
      // 这里的 `state` 对象是模块的局部状态
      state.count++;
    }
  },

  getters: {
    doubleCount(state) {
      return state.count * 2;
    }
  }
};

export default testModule;

运用:

1. 动态设置vuex

----动态注册
	createVuex() {
      const testVuex = {
        namespaced: true,
        state: () => ({
          whereIsSubTemp: "whereIsSubTemp"
        })
      };
      this.$store.registerModule("testVuex", testVuex);
    },
    
 ----注册检验
    this.$store..hasModule("testVuex")
 ----动态删除
 	this.$store.unregisterModule("testVuex")
 	
 	
2.使用vuex mapXxx 函数 将vuex 属性转为本地this属性
----动态获取 vuex store, getters
	import { mapState, mapGetters } from "vuex";
	computed: {
        ...mapState(["user", "test"]),
        ...mapGetters({ conterAdd: "conterAdd" })
  	},
----动态注册 vuex mutations, actions
        import { mapMutations, mapActions } from "vuex";
        methods: {
            ...mapMutations({ add: "increment" }),
            ...mapActions({
              addAsync: "incrementAsync"
            }),
    	}
3. vuex 模块化
----获取
	computed: {
	import { mapState, mapGetters } from "vuex";
        ...mapState({
          whereIsSubTemp: state => state.testVuex //testVuex为子模块名称
        })
      },

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值