Vuex中4个map方法的使用

1.mapState方法

用于帮助我们映射state中的数据为计算属性

 computed: {
    //靠程序员自己去写计算属性
    // sum() {
    //   return this.$store.state.sum;
    // },
    // school() {
    //   return this.$store.state.school;
    // },
    // subject() {
    //   return this.$store.state.subject;
    // },

    //借助mapState生成计算属性,从state中读取数据(对象写法)
    ...mapState({sum:'sum',school:'school',subject:'subject'})
    //借助mapState生成计算属性,从state中读取数据(数组写法)
    ...mapState(["sum", "school", "subject"])
 }

2.mapGetters方法

用于帮助我们映射getters中的数据为计算属性

computed: {
    // bigSum() {
    //   return this.$store.getters.bigSum;
    // },

    //借助mapGetters生成计算属性,从getters中读取数据(对象写法)
    ...mapGetters({bigSum:'bigSum'})
    //借助mapGetters生成计算属性,从getters中读取数据(数组写法)
    ...mapGetters(["bigSum"]),
  }

3.mapActions方法

用于帮助我们生成actions对话的方法,即:包含$store.dispatch(xxx)的函数

methods:{
    // incrementOdd() {
    //   this.$store.dispatch("jiaOdd", this.n);
    // },
    // incrementWait() {
    //   this.$store.dispatch("jiaWait", this.n);
    // },

    //借助mapActions生成对应的方法,方法中会调用dispatch去联系actions(对象写法)
    ...mapActions({ incrementOdd: "jiaOdd", incrementWait: "jiaWait" }),
    //借助mapActions生成对应的方法,方法中会调用dispatch去联系actions(对象写法)
    ...mapActions(["jiaOdd", "jiaWait"]),
}

4.mapMutations方法

用于帮助我们生成与actions对话的方法,即:包含$store.commit(xxx)的函数

methods: {
    // increment() {
    //   this.$store.commit("JIA", this.n);
    // },
    // decrement() {
    //   this.$store.commit("JIAN", this.n);
    // },

    //上边的方法需要传入参数n
    //借助mapMutations生成对应的方法,方法中会调用commit去联系mutations(对象写法)
    ...mapMutations({ increment: "JIA", decrement: "JIAN" }),
    //借助mapMutations生成对应的方法,方法中会调用commit去联系mutations(数组写法)
    //数组方法需要把键值对名称都改为一样的,此处先不改,用对象写法即可。
    ...mapMutations([JIA:'JIA',JIAN:'JIAN'])
}

注意:mapActions与mapMutations使用时,若需要传递参数,需要:在模板中绑定事件时传递好参数,否则参数是事件对象。

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值