• 辅助函数mapMutations详细解析


    原文链接;https://www.cnblogs.com/hjk1124/p/12672859.html

    mapMutations是vuex的mutation的辅助函数,用于在组件中映射mutation内的方法,以便在该组件中直接使用mutation里的方法 (说白了,就是一语法糖)

    1.在组件中导入vuex中的mapMutations:

    import { mapMutations } from 'vuex'

    2.在组件中导入mutation里的方法名:

    ...mapMutations([   //使用es6的拓展运算符
            'INCREASE_SHOPCART',   
            'DECREASE_SHOPCART'   
          ]) 
    //约定将mutation里的方法名为大写,并且导入时要给其加上引号
    

    这一步,是将mutation里的函数映射到组件里,在组件里 :

    this.INCREASE_SHOPCART === this.$store.commit('INCREASE_SHOPCART') //true

    在有参数的情况下,mutation的state默认参数可以省略 :

    this.INCREASE_SHOPCART(id) === this.$store.commit('INCREASE_SHOPCART',id) //true

    举个栗子:点击btn按钮增减商品数量

    • 组件dom :
    //shopCart.vue 
    //template
      <button class="fl" @click='decrease(item.id)'>-</button>
      <input type="number" class="fl" v-model="item.count"  >
      <button class="fl" @click='increase(item.id)'>+</button>
    • mutations :
    //mutations.js
    INCREASE_SHOPCART(state,id){
        state.shopCartData.forEach(e=>{
          if(e.id === id){
            e.count ++
          }
        })
      },
      DECREASE_SHOPCART(state,id){
        state.shopCartData.forEach(e=>{
          if(e.id === id && e.count >1){
            e.count --
          }
        })
      }
    • 组件里的methods:
    import { mapMutations } from 'vuex' // 先从vuex里导入 mapMutations
    methods:{
         ...mapMutations([  
            'INCREASE_SHOPCART', //将mutation里的方法映射到该组件内
            'DECREASE_SHOPCART'  //等同于this.$store.commit('DECREASE_SHOPCART')  
          ]),
         increase(id){
            this.INCREASE_SHOPCART(id)
    //由于上一步已经将mutation映射到组件内,所以组件可以直接调用INCREASE_SHOPCART  
         }
         decrease(id){
            this.DECREASE_SHOPCART(id)
    //同理
         }
    }

    以上。

  • 相关阅读:
    [转载] kill命令
    [转载] Linux的Top命令解析
    json互相转换
    C# 13位时间戳(unix时间戳)
    第八篇:cx_Oracle出现的问题
    linux:eth网卡对应的物理网口判断
    ls显示前几行或后几行数据
    第七篇:suds.TypeNotFound: Type not found: '(string, http://schemas.xmlsoap.org/soap/encoding/, )'
    第六篇:python中numpy.zeros(np.zeros)的使用方法
    第五篇:selenium调用IE问题(Protected Mode settings are not the same for all zones)
  • 原文地址:https://www.cnblogs.com/fsg6/p/14398639.html
Copyright © 2020-2023  润新知