今天写一个商品列表的选择

需求是在点击增加和减少按钮时判断数量给出提示


刚开始想的是每次点击的时候判断商品数量是否符合规则,不符合的话就my.showToash
reduce(e) {
if (list[e.currentTarget.dataset.idx].count == 0) {
my.showToast({
content: '商品数量最少为0',
duration: 800,
}
})
}
} else {
let now = 0
list[e.currentTarget.dataset.idx].count--
list.forEach((item, index) => {
now += item.count
})
this.setData({
productList: list,
now: now
})
}
},
plus(e) {
if (this.data.now == that.props.max) {
my.showToast({
content: '最多只能选择' + that.props.max + '个商品',
duration: 800,
}
})
}
} else {
let now = 0
const list = this.props.productList
list[e.currentTarget.dataset.idx].count++
list.forEach((item, index) => {
now += item.count
})
this.setData({
productList: list,
now: now
})
}
}
},
但是有个问题是如果客户脑子被门夹了,在选够三个商品后还疯狂点击增加按钮,或者疯狂点击商品数量为0的商品的减少按钮,就会弹出N多个toast,又因为我给每个toast的动画时间设置的0.8s,就会出现N多个toast排队弹出的情况。
可能你页面都切换了toast还在排队弹出。。。。。。
为了解决这个问题所以加了一个toastable的字段来判断当前是否有toast在显示,如果有的话就不调用showTaost,然后在每个toast动画结束后调用complete回调方法来改变toastable的状态,这样就能避免脑残客户的找茬行为了
reduce(e) {
let that = this
const list = this.props.productList
if (list[e.currentTarget.dataset.idx].count == 0) {
// 如果当前没有toast在显示,就弹出toast
if (that.data.toastable) {
that.setData({
toastable: false
})
console.log(111)
my.showToast({
content: '商品数量最少为0',
duration: 800,
// toast结束的回调函数
complete() {
that.setData({
toastable: true
})
}
})
}
} else {
let now = 0
list[e.currentTarget.dataset.idx].count--
list.forEach((item, index) => {
now += item.count
})
this.setData({
productList: list,
now: now
})
}
},
plus(e) {
let that = this
if (this.data.now == that.props.max) {
if (that.data.toastable) {
that.setData({
toastable: false
})
console.log(111)
my.showToast({
content: '最多只能选择' + that.props.max + '个商品',
duration: 800,
complete() {
that.setData({
toastable: true
})
}
})
}
} else {
let now = 0
const list = this.props.productList
list[e.currentTarget.dataset.idx].count++
list.forEach((item, index) => {
now += item.count
})
this.setData({
productList: list,
now: now
})
}
}
},
2021.02.20补充:
今天看博客看到一个名词——节流函数。想起来之前做过类似的需求,于是回来补充一下:
https://segmentfault.com/a/1190000018257074?utm_source=sf-related
其实原理都是用一个“锁变量”来控制事件的触发。只不过上文使用的小程序的api是在complete方法里“解锁”,节流和防抖是自定义了间隔时间。