小程式 WXSS wx:key是怎麼使用的?當清單中的項目動態的改變的時候,我們需要設定wx:key,Now you can provide attr "wx:key" for a "wx:for" to improve performance.
#
#在循環數組的時候有時候會出現如下面的提示。
VM1364:2 ./index/index.wxml (anonymous) @ VM1364:2 VM1364:3 Now you can provide attr "wx:key" for a "wx:for" to improve performance. > 1 | <view wx:for="{{data}}" class="block" style="{{item.style}}"> | ^ 2 | Block{{index}} 3 | <view>{{item.title}}</view> 4 | </view> (anonymous) @ VM1364:3
官方對wx:key的解釋:
#如果清單中項目的位置會動態改變或有新的項目加入清單中,並且希望清單中的專案維持自己的特徵和狀態(如 <input>
中的輸入內容, <switch></switch>
的選取狀態),需要使用 wx :key
來指定清單中項目的唯一的識別碼。
當清單中的項目動態的改變的時候,我們需要設定wx:key,如果我們不設置,會出現如上圖的情況,我們想要加入數據4,在左圖中資料4被排在了亂的位置,這個是我們不希望的,因此為了防止這種情況的出現,我們設定wx:key.
wx:key
的值以兩種形式提供:
1.字串,代表在for 迴圈的array 中item 的某個property,該property 的值需要是列表中唯一的字串或數字,且不能動態改變。
2.保留關鍵字this 代表在for 迴圈中的item 本身,這種表示需要item 本身是一個唯一的字串或數字,如:
當資料改變觸發渲染層重新渲染的時候,會校正帶有key 的元件,框架會確保他們被重新排序,而不是重新創建,以確保使元件保持自身的狀態,並且提高列表渲染時的效率。
<switch wx:for="{{objectArray}}" wx:key="unique" > {{item.id}} </switch> <button bindtap="switch"> Switch </button> <button bindtap="addToFront"> Add to the front </button> <switch wx:for="{{numberArray}}" wx:key="*this" > {{item}} </switch> <button bindtap="addNumberToFront"> Add to the front </button>
Page({ data: { objectArray: [ {id: 5, unique: 'unique_5'}, {id: 4, unique: 'unique_4'}, {id: 3, unique: 'unique_3'}, {id: 2, unique: 'unique_2'}, {id: 1, unique: 'unique_1'}, {id: 0, unique: 'unique_0'}, ], numberArray: [1, 2, 3, 4] }, switch: function(e) { const length = this.data.objectArray.length for (let i = 0; i < length; ++i) { const x = Math.floor(Math.random() * length) const y = Math.floor(Math.random() * length) const temp = this.data.objectArray[x] this.data.objectArray[x] = this.data.objectArray[y] this.data.objectArray[y] = temp } this.setData({ objectArray: this.data.objectArray }) }, addToFront: function(e) { const length = this.data.objectArray.length this.data.objectArray = [{id: length, unique: 'unique_' + length}].concat(this.data.objectArray) this.setData({ objectArray: this.data.objectArray }) }, addNumberToFront: function(e){ this.data.numberArray = [ this.data.numberArray.length + 1 ].concat(this.data.numberArray) this.setData({ numberArray: this.data.numberArray }) } })
相關推薦:
以上是小程式 WXSS wx:key的作用以及使用實例的詳細內容。更多資訊請關注PHP中文網其他相關文章!

熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

Dreamweaver Mac版
視覺化網頁開發工具

VSCode Windows 64位元 下載
微軟推出的免費、功能強大的一款IDE編輯器

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)

Safe Exam Browser
Safe Exam Browser是一個安全的瀏覽器環境,安全地進行線上考試。該軟體將任何電腦變成一個安全的工作站。它控制對任何實用工具的訪問,並防止學生使用未經授權的資源。

Dreamweaver CS6
視覺化網頁開發工具