自己的第一個點餐小程序,主要包括左右菜單聯(lián)動、點擊數(shù)量加減、菜單和購物車數(shù)量可以同步加減、購物車動畫等,純前端實現(xiàn)
大致的功能樣式如下圖展示:
代碼塊
主要代碼塊:
// 點擊左側(cè)分類切換右側(cè)菜品 changeRightMenu: function (e) { var classify = e.target.dataset.id;// 獲取點擊項的id var foodList = this.data.foodList; var allFoodList = this.data.allFoodList; var newFoodList = []; if (classify == 0) {//選擇了全部選項 this.setData({ curNav: classify, foodList: allFoodList }) } else { //選擇了其他選項 for (var i in allFoodList) { if (allFoodList[i].catid == classify) { newFoodList.push(allFoodList[i]) } } this.setData({ // 右側(cè)菜單當(dāng)前顯示第curNav項 curNav: classify, foodList: newFoodList }) } }, // 購物車及菜單中增加數(shù)量 addCount: function (e) { var id = e.currentTarget.dataset.id;[這里寫鏈接內(nèi)容](http://download.csdn.net/download/m0_37543652/10019843%20%20%E6%BA%90%E7%A0%81%E4%B8%8B%E8%BD%BD%E5%9C%B0%E5%9D%80) var arr = wx.getStorageSync('cart') || []; var f = false; for (var i in this.data.foodList) {// 遍歷菜單找到被點擊的菜品,數(shù)量加1 if (this.data.foodList[i].id == id) { this.data.foodList[i].quantity += 1; if (arr.length > 0) { for (var j in arr) {// 遍歷購物車找到被點擊的菜品,數(shù)量加1 if (arr[j].id == id) { arr[j].quantity += 1; f = true; try { wx.setStorageSync('cart', arr) } catch (e) { console.log(e) } break; } } if (!f) { arr.push(this.data.foodList[i]); } } else { arr.push(this.data.foodList[i]); } try { wx.setStorageSync('cart', arr) } catch (e) { console.log(e) } break; } } this.setData({ cartList: arr, foodList: this.data.foodList }) this.getTotalPrice(); }, // 定義根據(jù)id刪除數(shù)組的方法 removeByValue: function (array, val) { for (var i = 0; i < array.length; i++) { if (array[i].id == val) { array.splice(i, 1); break; } } }, // 購物車減少數(shù)量 minusCount: function (e) { var id = e.currentTarget.dataset.id; var arr = wx.getStorageSync('cart') || []; for (var i in this.data.foodList) { if (this.data.foodList[i].id == id) { this.data.foodList[i].quantity -= 1; if (this.data.foodList[i].quantity <= 0) { this.data.foodList[i].quantity = 0; } if (arr.length > 0) { for (var j in arr) { if (arr[j].id == id) { arr[j].quantity -= 1; if (arr[j].quantity <= 0) { this.removeByValue(arr, id) } if (arr.length <= 0) { this.setData({ foodList: this.data.foodList, cartList: [], totalNum: 0, totalPrice: 0, }) this.cascadeDismiss() } try { wx.setStorageSync('cart', arr) } catch (e) { console.log(e) } } } } } } this.setData({ cartList: arr, foodList: this.data.foodList }) this.getTotalPrice(); },