數據:三層嵌套
index.wxml 頁面
<!-- 菜單標簽 --> <view class='menu_label'> <view class='label_ul'> <view wx:for="{{ menuList }}" wx:key='' class="{{ label_index == index ? 'label_lis' : 'label_li' }}" bindtap='menuList' id="{{ index }}">{{ item.title }}</view> </view> </view> <!-- 圖書內容 --> <view class='book_sec'> <view class='book_ul' wx:for="{{ bookUl }}" wx:key='' wx:for-item="secUl" wx:if="{{ label_index == index }}" id="{{ index }}"> <view class='book_li' wx:for='{{ secUl.bookSec }}' wx:key='' wx:for-item="secLi"> <view class='book_ol'> <view class='book_ol_li' wx:for='{{ secLi.bookList }}' wx:key='' wx:for-item="item"> <view class='book_free b'>免費閱讀</view> <image src='{{ item.img }}'></image> <view class='book_people b'>100006人在讀</view> </view> </view> </view> </view> </view> |
Page({ /** * 頁面的初始數據 */ data: { menuList: [ { title: '全部' }, { title: '文學' }, { title: '技術類' }, { title: '社會科學' }, { title: '設計' }, { title: '技術類' }, { title: '社會科學' }, ], label_index: 0, bookUl: [ { bookSec: [ { bookList: [ { img: '../../img/img1_icon.png' }, { img: '../../img/img2_icon.png' }, { img: '../../img/img3_icon.png' }, ] }, { bookList: [ { img: '../../img/img4_icon.png' }, { img: '../../img/img5_icon.png' }, ] } ] }, { bookSec: [ { bookList: [ { img: '../../img/img6_icon.png' }, { img: '../../img/img5_icon.png' }, { img: '../../img/img4_icon.png' } ] }, { bookList: [ { img: '../../img/img7_icon.png' } ] } ] }, { bookSec: [ { bookList: [ { img: '../../img/img7_icon.png' }, { img: '../../img/img2_icon.png' }, { img: '../../img/img1_icon.png' }, ] }, { bookList: [ { img: '../../img/img3_icon.png' }, { img: '../../img/img4_icon.png' }, { img: '../../img/img6_icon.png' } ] } ] }, ] /** * 菜單點擊切換內容 */ menuList: function (e) { let that = this; // console.log(e); var id = e.target.id; that.setData({ label_index: id }) } }, }) |
如果列表中項目的位置會動態改變或者有新的項目添加到列表中,并且希望列表中的項目保持自己的特征和狀態(如 <input/> 中的輸入內容,<switch/> 的選中狀態),需要使用 wx:key 來指定列表中項目的唯一的標識符。
如不提供 wx:key,會報一個 warning, 如果明確知道該列表是靜態,或者不必關注其順序,可以選擇忽略。
wx:key 的值以兩種形式提供
1)字符串,代表在 for 循環的 array 中 item 的某個 property,該 property 的值需要是列表中唯一的字符串或數字,且不能動態改變。
2)保留關鍵字 *this 代表在 for 循環中的 item 本身,這種表示需要 item 本身是一個唯一的字符串或者數字,如:
當數據改變觸發渲染層重新渲染的時候,會校正帶有 key 的組件,框架會確保他們被重新排序,而不是重新創建,以確保使組件保持自身的狀態,并且提高列表渲染時的效率。
最后效果圖