(三).wx:key
如果列表中项目的位置会动态改变或者有新的项目添加到列表中,并且希望列表中的项目保持自己的特征和状态(如 <input/>
中的输入内容,<switch/>
的选中状态),需要使用 wx:key
来指定列表中项目的唯一的标识符。
- 字符串,代表在 for 循环的 array 中 item 的某个 property,该 property 的值需要是列表中唯一的字符串或数字,且不能动态改变。
- 保留关键字
*this
代表在 for 循环中的 item 本身,这种表示需要 item 本身是一个唯一的字符串或者数字,如:
如不提供 wx:key
,会报一个 warning
, 如果明确知道该列表是静态,或者不必关注其顺序,可以选择忽略。
二.案例
1.用户中心列表
- <span style="box-sizing: border-box; font-family: 'Comic Sans MS'; font-size: 18px;"><!--list.wxml-->
- <block wx:for="{{userListInfo}}">
- <view class="weui_cell">
- <view class="weui_cell_hd">
- <image src="{{item.icon}}"></image>
- </view>
- <view class="weui_cell_bd">
- <view class="weui_cell_bd_p"> {{item.text}} </view>
- </view>
- <view wx:if="{{item.isunread}}" class="badge">{{item.unreadNum}}</view>
- <view class="with_arrow"></view>
- </view>
- </block></span>
- <span style="box-sizing: border-box; font-family: 'Comic Sans MS'; font-size: 18px;">/**list.wxss**/
- .weui_cell {
- position: relative;
- display: flex;
- padding: 15px;
- -webkit-box-align: center;
- -ms-flex-align: center;
- align-items: center;
- border-bottom: 1px solid #dadada;
- }
- .weui_cell_hd {
- display: inline-block;
- width: 20px;
- margin-right: 5px;
- }
- .weui_cell_hd image {
- width: 100%;
- height: 20px;
- vertical-align: -2px;
- }
- .weui_cell_bd {
- display: inline-block;
- }
- .weui_cell_bd_p {
- font-size: 14px;
- color: #939393;
- }
- .badge {
- position: absolute;
- top: 18px;
- right: 40px;
- width: 15px;
- height: 15px;
- line-height: 15px;
- background: #ff0000;
- color: #fff;
- border-radius: 50%;
- text-align: center;
- font-size: 8px;
- }
- .with_arrow {
- position: absolute;
- top: 18px;
- right: 15px;
- width: 15px;
- height: 15px;
- background-image: url(../../dist/images/icon-arrowdown.png);
- background-repeat: no-repeat;
- background-size: 100% 100%;
- }</span>
- <span style="box-sizing: border-box; font-family: 'Comic Sans MS'; font-size: 18px;">//list.js
- var app = getApp()
- Page( {
- data: {
- userInfo: {},
- userListInfo: [ {
- icon: '../../dist/images/iconfont-dingdan.png',
- text: '我的订单',
- isunread: true,
- unreadNum: 2
- }, {
- icon: '../../dist/images/iconfont-card.png',
- text: '我的代金券',
- isunread: false,
- unreadNum: 2
- }, {
- icon: '../../dist/images/iconfont-icontuan.png',
- text: '我的拼团',
- isunread: true,
- unreadNum: 1
- }, {
- icon: '../../dist/images/iconfont-shouhuodizhi.png',
- text: '收货地址管理'
- }, {
- icon: '../../dist/images/iconfont-kefu.png',
- text: '联系客服'
- }, {
- icon: '../../dist/images/iconfont-help.png',
- text: '常见问题'
- }]
- },
- onLoad: function() {
- var that = this
- //调用应用实例的方法获取全局数据
- app.getUserInfo( function( userInfo ) {
- //更新数据
- that.setData( {
- userInfo: userInfo
- })
- })
- }
- })</span>