• 【Vue项目复习笔记】Vuex-action返回Promise-mapActions


    我们现在想要做一个弹窗效果,也就是在详情页中点击加入购物车以后弹出加入购物车成功的弹窗。过一会儿这个弹窗会消失。这种弹窗有一个固定的名字,叫做toast()土司。
    实现这个效果第一步我们需要监听加入购物车的点击事件。在detail中methods里面

    addCart(){
          //1.获取购物车需要展示的信息
          const product={}
          product.image=this.topImages[0]
          product.title=this.goods.title;
          product.desc=this.goods.desc;
          product.price=this.goods.realPrice;
          product.iid=this.iid;
    
    
          //2、将商品添加到购物车
          this.$store.dispatch('addCart',product)
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    我们可以在添加到购物车下面做添加购物车成功吗?不一定,因为里面做了很多操作,只能等到里面的操作已经完成以后才可以添加购物车成功,并不是一点击addCart就添加购物车成功了。那怎么知道里面的操作有没有完成呢?dispatch 它会返回一个promise,所以在actions.js里面将addCart里面的东西new 一个promise

     addCart(context, payload){
      return  new Promise((resolve,reject)=>{
        //1.查找之前数组是否有该商品
        let oldProduce=context.state.cartList.find(item=>item.iid===payload.iid)
    
        //2.判断oldProduce
        if(oldProduce){ //数量+1
          // oldProduce.count+=1
          context.commit('addCounter',oldProduce)
          resolve('当前商品数量+1')
        }else{  //添加新的商品
          payload.count=1
          // context.state.cartList.push(payload)
          context.commit('addCart', payload)
          resolve('添加了新的商品')
        }
      })
      }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18

    我们上面的这个Promise可以在

     this.$store.dispatch('addCart',product)
    
    • 1

    这里的dispatch接收,所以我们可以在后面添加then

      this.$store.dispatch('addCart',product).then(res=>{
            console.log(res);
          })
    
    • 1
    • 2
    • 3

    具体效果如下:
    请添加图片描述
    上面的方法是通过 this.$store.dispatch调用addCart函数,这个addCart函数是actions里面的addCart函数。
    如果我们不想通过上面方法调用,我们想直接通过this.addCart(product).then(res)这种方法,但是this.是调用自己的方法,但是它自己并没有这种方法,所以它可以将actions.js里面addCart的方法映射到detail里面。通过mapGetters

    import {mapActions} from 'vuex';
    
    • 1

    然后在methods中

    ...mapActions(['addCart']),
    
    • 1

    然后在addCart函数里面:

     this.addCart(product).then(res=>{
            console.log(res);
          })
    
    • 1
    • 2
    • 3

    此时出现了一个问题
    在这里插入图片描述
    意思是超出最大调用堆栈大小。
    我仔细看了一下,我觉得最大的可能是命名的问题,因为我这个定义的函数名字也叫addCart,在actions里面也是叫addCart,所以这里的addCart调用的时候定义不明,

     ...mapActions({ 
          add:'addCart'
        }),
    
    • 1
    • 2
    • 3
     this.add(product).then(res=>{
           console.log(res);
         })
    
    • 1
    • 2
    • 3

    结果果然证明是对的,效果和上上图相同。

  • 相关阅读:
    MySQL——表的插入
    C++ 单例模式
    java连接数据库SQL注入问题的解决
    数据分析:密度图
    wpf中的StaticResource和DynamicResource
    大数据开发(Hadoop面试真题-卷九)
    暑期JAVA学习(33)线程安全
    GoogLeNet的不同版本
    Missing xsltproc. Doc not built.
    【数据结构初阶】堆&&堆的实现&&堆排序&&TOP-K
  • 原文地址:https://blog.csdn.net/qq_40992225/article/details/126289859