uniapp 开发微信小程序控制台提示 Now you can provide attr `wx:key` for a `wx:for` to improve performance

warning: 这篇文章距离上次修改已过793天,其中的内容可能已经有所变动。

问题

每当使用微信开发者工具预览小程序时,均会在控制台(Console)看到警告(Warn)信息:Now you can provide attr wx:key for a wx:for to improve performance

原因

uniapp的v-for写法导致。

修改前的写法如下:

<view class="comment-content" v-for="(item,index) in commentList">
    <!-- 评论用户头像 -->
    <view class="comment-content-left">
        <image class="comment-content-headImage" :src="item.formHead" mode="center"></image>
    </view>
    <view class="comment-content-right">
        <!-- 评论用户名 -->
        <view class="comment-content-name">{{item.formNick}}</view>
        <!-- 评论内容 -->
        <view class="comment-content-text">{{item.content}}</view>
        <!-- 评论日期 -->
        <view class="comment-content-time">{{item.commentTime}}</view>
    </view>
</view>

解决方法

v-for 搭配 key 使用。

解决后的写法如下:

<view class="comment-content" v-for="(item,index) in commentList" :key="index">
    <!-- 评论用户头像 -->
    <view class="comment-content-left">
        <image class="comment-content-headImage" :src="item.formHead" mode="center"></image>
    </view>
    <view class="comment-content-right">
        <!-- 评论用户名 -->
        <view class="comment-content-name">{{item.formNick}}</view>
        <!-- 评论内容 -->
        <view class="comment-content-text">{{item.content}}</view>
        <!-- 评论日期 -->
        <view class="comment-content-time">{{item.commentTime}}</view>
    </view>
</view>

添加新评论