我们现在想要做一个弹窗效果,也就是在详情页中点击加入购物车以后弹出加入购物车成功的弹窗。过一会儿这个弹窗会消失。这种弹窗有一个固定的名字,叫做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)
}
我们可以在添加到购物车下面做添加购物车成功吗?不一定,因为里面做了很多操作,只能等到里面的操作已经完成以后才可以添加购物车成功,并不是一点击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('添加了新的商品')
}
})
}
我们上面的这个Promise可以在
this.$store.dispatch('addCart',product)
这里的dispatch接收,所以我们可以在后面添加then
this.$store.dispatch('addCart',product).then(res=>{
console.log(res);
})
具体效果如下:
上面的方法是通过 this.$store.dispatch调用addCart函数,这个addCart函数是actions里面的addCart函数。
如果我们不想通过上面方法调用,我们想直接通过this.addCart(product).then(res)这种方法,但是this.是调用自己的方法,但是它自己并没有这种方法,所以它可以将actions.js里面addCart的方法映射到detail里面。通过mapGetters
import {mapActions} from 'vuex';
然后在methods中
...mapActions(['addCart']),
然后在addCart函数里面:
this.addCart(product).then(res=>{
console.log(res);
})
此时出现了一个问题
意思是超出最大调用堆栈大小。
我仔细看了一下,我觉得最大的可能是命名的问题,因为我这个定义的函数名字也叫addCart,在actions里面也是叫addCart,所以这里的addCart调用的时候定义不明,
...mapActions({
add:'addCart'
}),
this.add(product).then(res=>{
console.log(res);
})
结果果然证明是对的,效果和上上图相同。