詳解小程式開發之wx:key

Y2J
發布: 2017-05-12 11:30:27
原創
2141 人瀏覽過

這篇文章主要介紹了微信小程式wx:key詳細介紹的相關資料,並附簡單程式碼實例,幫助大家學習理解,需要的朋友可以參考下

微信小程序wx:key 在自己學習的時候不是多明白到底是怎麼回事,經過上網查閱資料,整理下:

  個人感覺官方給出的例子不是很明確,官方解釋如下:

wx:key

如果清單中項目的位置會動態改變或有新的項目新增到清單中,並且希望清單中的項目保持自己的特徵和狀態(如 中的輸入內容, 的選取狀態),需要使用wx:key 來指定清單中項目的唯一的識別碼。

wx:key 的值以兩種形式提供

字串,代表在for 循環array 中item 的某個property,該property 的值需要是清單中唯一的字串或數字,且不能動態改變。

保留關鍵字*this 代表在for 迴圈中的item 本身,這種表示需要item 本身是一個唯一的字串或數字,如:

當資料改變觸發渲染層重新渲染的時候,會校正帶有key 的元件,框架會確保他們被重新排序,而不是重新創建,以確保使組

件保持自身的狀態,並且提高清單渲染時的效率。

如不提供 wx:key,會報一個 warning, 如果明確知道該列表是靜態,或者不必關注其順序,可以選擇忽略。

範例程式碼:


<switch wx:for="{{objectArray}}" wx:key="unique" style="display: block;"> {{item.id}} </switch>
<button bindtap="switch"> Switch </button>
<button bindtap="addToFront"> Add to the front </button>

<switch wx:for="{{numberArray}}" wx:key="*this" style="display: block;"> {{item}} </switch>
<button bindtap="addNumberToFront"> Add to the front </button>
Page({
 data: {
  objectArray: [
   {id: 5, unique: &#39;unique_5&#39;},
   {id: 4, unique: &#39;unique_4&#39;},
   {id: 3, unique: &#39;unique_3&#39;},
   {id: 2, unique: &#39;unique_2&#39;},
   {id: 1, unique: &#39;unique_1&#39;},
   {id: 0, unique: &#39;unique_0&#39;},
  ],
  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: &#39;unique_&#39; + 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
  })
 }
})
登入後複製

這裡寫下個人的理解,有什麼不對的地方希望大家指正:以< switch>為例,如果沒有wx:key,選中其中的某個按鈕的時候,改變其順序或添加選項的時,選中的按鈕時不回跟隨上個按鈕改變順序的,會一直在固定位子,如果有wx:key則相反,適用於列表或其他標籤可以改變順序或添加項目的情況

【相關推薦】

1 . 微信小程式完整原始碼

2. 追格微信小程式應用程式商店

#

以上是詳解小程式開發之wx:key的詳細內容。更多資訊請關注PHP中文網其他相關文章!

相關標籤:
來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
最新問題
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!