zoukankan      html  css  js  c++  java
  • Live2d Test Env

    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)
    //同理
         }
    }
    

    以上。

  • 相关阅读:
    HDU 4278 Faulty Odometer 8进制转10进制
    hdu 4740 The Donkey of Gui Zhou bfs
    hdu 4739 Zhuge Liang's Mines 随机化
    hdu 4738 Caocao's Bridges tarjan
    Codeforces Gym 100187M M. Heaviside Function two pointer
    codeforces Gym 100187L L. Ministry of Truth 水题
    Codeforces Gym 100187K K. Perpetuum Mobile 构造
    codeforces Gym 100187J J. Deck Shuffling dfs
    codeforces Gym 100187H H. Mysterious Photos 水题
    windows服务名称不是单个单词的如何启动?
  • 原文地址:https://www.cnblogs.com/hjk1124/p/12672859.html
Copyright © 2011-2022 走看看