//原始代碼
setCollect: Debounce(function() {
//這里防抖 500ms內只執行最后一次 所以每次都 延遲500ms顯得很卡頓
if (this.isLogin === false) {
toLogin();
} else {
let that = this;
if (this.storeInfo.userCollect) {
//取消收藏-請求網絡-成功 再改成圖標狀態 ↓ 所以會有網絡延遲,再次延遲卡頓
collectDel(this.storeInfo.id).then(res => {
that.$set(that.storeInfo, 'userCollect', !that.storeInfo.userCollect);
return that.$util.Tips({
title: res.msg
});
});
} else {
//收藏-請求服務器- 成功了-再改成圖標狀態 ↓ 所以會有網絡延遲,再次延遲卡頓
collectAdd(this.storeInfo.id).then(res => {
that.$set(that.storeInfo, 'userCollect', !that.storeInfo.userCollect);
return that.$util.Tips({
title: res.msg
});
});
}
}
}),
//這樣雙重延遲下來 就顯得很卡了
data() {
let that = this;
return {
userCollect: '', //新增每次點擊時記錄初始收藏狀態
.......
.......
.......
};
},
//收藏商品-優化版
setCollect() {
//未登錄跳轉登錄頁
if (this.isLogin === false) return toLogin()
//記錄本次 點擊前, 收藏的初始狀態(收藏/未收藏), 單位時間內點擊,只記錄一次
if(this.userCollect === '') this.userCollect = this.storeInfo.userCollect
//視覺優先 提前立刻改變圖標狀態反饋給用戶 提升用戶體驗,隨便他亂點 只改變圖標狀態
this.storeInfo.userCollect = !this.storeInfo.userCollect
//振動反饋 不需要的話 請注釋
uni.vibrateShort()
this.getCollect()
},
getCollect: Debounce(function() { //防抖放在后面減少請求
let collectStatus = this.storeInfo.userCollect
// 再次減少請求-判斷是否需請求服務器更新收藏狀態
//例如客戶本來就是 ‘已收藏’,快速點了n次后 還是 ‘已收藏’
//那么不需要請求服務器
let whether = this.userCollect !== collectStatus
this.userCollect = '' //清空本次記錄的 初始收藏狀態
if (whether) {
let id = this.id
//判斷請求接口 收藏/取消收藏
let collectAction = collectStatus ? collectAdd(id) : collectDel(id)
collectAction.then(res => {
return this.$util.Tips({
title: res.msg //成功提示
});
}).catch(err => {
// 網絡或者服務器等原因...導致請求失敗,這種情況極少會發生
// 前面提前改了圖標狀態,如果服務器端操作失敗,給他再恢復原來的狀態即可
this.storeInfo.userCollect = !collectStatus
this.$util.Tips({
title: '操作失敗,請重試', // 失敗提示
});
});
}
}),