微信小程序的分類功能思路
實現思路
1.把屏幕當成一個固定的盒子,然后把盒子分成兩邊,並讓盒子的每一邊都能夠滾動。 2.通過將左側邊欄元素的id和右邊內容的categoryId進行匹配,渲染展示相同id的內容
頁面data定義的初始數據
/** * 頁面的初始數據 */
data: { classify_sidebar: [], //左側邊欄內容的數組 classify_content: [], //右邊內容元素的數組 list: 124849, //綁定切換時的id },
1.先利用文檔對左邊的側邊欄進行布局和渲染
<!-- 左側邊欄 --> <scroll-view class="left" scroll-y="true"> <view class="classify_sidebar"> <view class="{{item.id===list?'classify_active':''}}" data-id="{{item.id}}" catchtap="change" wx:for='{{classify_sidebar}}' wx:key="index">{{item.name}}</view> </view> </scroll-view>
class="{{item.id===list?'classify_active':''}}"
運用三目運算符來給當前選中的元素切換樣式(紅色下划線),如果說當前元素的id和我們設置的list相同就添加類名加樣式
data-id="{{item.id}}" 通過自定義來傳參,根據左側邊欄元素的id來匹配右邊的內容
catchtap="change"
當用戶點擊不同的側邊欄目錄時候,根據 data-id 去從數據庫獲取新的數據,
渲染到左側,並且修改 list的值,使新樣式添加到點擊的元素上
change(e) { let {id} = e.currentTarget.dataset this.contentFn(id) //封裝的方法 this.setData({ list: id }) wx.showLoading({ title: '加載中', }) setTimeout(() => { wx.hideLoading() }, 1000) },
2.右邊內容的布局和渲染
<scroll-view class="right" scroll-y="true"> <!-- 右邊的內容部分 --> <view class="classify_content"> <!-- 右邊內容的列表 --> <text wx:if="{{classify_content.length == 0}}">————— 暫無數據 ————</text> <view class="classify_content_list" wx:if="{{classify_content.length > 0}}" wx:for="{{classify_content}}" wx:key="index"> <!-- 右邊內容的列表圖片 --> <image src="{{item.pic}}"></image> <text class="classify_content_list_right_title">{{item.name}}</text> </view> <!-- 右邊內容的列表結束 --> </view> <!-- 右邊的內容部分結束 --> </scroll-view> wx:if="{{classify_content.length == 0}}">
如果說右邊相對應的商品數量為零就顯示 “暫無數據”
// 封裝 contentFn(tar) { let arr = [] wx.request({ url: 'https://api.it120.cc/lsn/shop/goods/list', success: res => { if (res.statusCode == 200) { res.data.data.forEach((item, v) => { if (item.categoryId == tar) { arr.push(item) } }) this.data.classify_content = arr.reverse() this.setData({ classify_content: this.data.classify_content }) } } }) },
思路
首先封裝個方法然后在點擊切換左側邊欄的時候進行調用
第一步:通過wx.request()去請求右邊所有內容
第二步:如果說狀態碼200表示“服務器成功返回網頁”
第三步:通過循環右邊的內容,如果說當前categoryId等同於我們點擊左側邊欄的id,數組push添加,同時倒序並且賦值給我們自己定義的數組和進行試圖更新