重庆小潘seo博客

当前位置:首页 > 重庆网络营销 > 小潘杂谈 >

小潘杂谈

小程序 WXSS wx:key的作用以及使用实例

时间:2020-09-12 14:30:06 作者:重庆seo小潘 来源:
小程序 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) @ VM1

小程序 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:2VM1364:3Now you can provide attr "wx:key" for a "wx:for" to improve performance.> 1 | <view wx:for="{{data}}"> 官方对wx:key的解释:

如果列表中项目的位置会动态改变或者有新的项目添加到列表中,并且希望列表中的项目保持自己的特征和状态(如 <input/> 中的输入内容, <switch/> 的选中状态),需要使用 wx:key 来指定列表中项目的唯一的标识符。

小程序 WXSS 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.lengthfor (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.lengththis.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})}}) 相关推荐:

详解小程序开发之wx:key

微信小程序 wx:key详细介绍以上就是小程序 WXSS wx:key的作用以及使用实例的详细内容,更多请关注小潘博客其它相关文章!