wx:for渲染的列表,切换template时很慢很慢
发布于 6 年前 作者 baiyang 2400 次浏览 来自 问答

如下wxml的for循环:

<template is=“tpl-{{viewMode}}” wx:for="{{products}}" data="{{pd: item, index}}" wx:key=“id”/>

js里,设置不同的viewMode(page.setData({viewMode}))时渲染会很慢,而且多次切换越来越慢。

慢的是windows桌面开发工具,真机(安卓和iOS都)试了不算慢。

2 回复

<!–demo.wxml–>

<template name=“tpl-row”>

  <view class=“item-row” catchtap=“onViewItem” data-index="{{index}}">

    <text class=“row code”>{{item.code}}</text>

    <text class=“row name”>{{item.name}}</text>

  </view>

</template>

<template name=“tpl-card”>

  <view class=“item-card” catchtap=“onViewItem” data-index="{{index}}">

    <text class=“card code”>{{item.code}}</text>

    <text class=“card name”>{{item.name}}</text>

  </view>

</template>

<view class=“page-header”>Demo</view>

<scroll-view class=“page-body”>

    <template is=“tpl-{{viewMode}}” wx:for="{{items}}" data="{{item, index}}" wx:key=“id”/>

</scroll-view>

<view class=“page-footer”>

  <button catchtap=“switchViewMode” data-view-mode=“row”>Row</button>

  <button catchtap=“switchViewMode” data-view-mode=“card”>Card</button>

</view>

/* demo.wxss */

page{

  display: flex;

  flex-direction: column;

  height: 100%;

  width: 100%;

}

.page-header{

  display: flex;

  justify-content: center;

}

.page-body{

  display: flex;

  flex: 1;

  height: 100%;

  flex-direction: column;

}

.page-footer{

  display: flex;

  justify-content: center;

}

.page-footer button{

  flex: 1;

}

//demo.js

Page({

  data:{

    items: [

      {id: 1, code: ‘code1’, name:‘名称1’},

      {id: 2, code: ‘code2’, name:‘名称2’},

      {id: 3, code: ‘code3’, name:‘名称3’},

      {id: 4, code: ‘code4’, name:‘名称4’},

      {id: 5, code: ‘code5’, name:‘名称5’},

      {id: 6, code: ‘code6’, name:‘名称6’},

      {id: 7, code: ‘code7’, name:‘名称7’},

      {id: 8, code: ‘code8’, name:‘名称8’},

      {id: 9, code: ‘code9’, name:‘名称9’},

      {id: 10, code: ‘code10’, name:‘名称10’},

      {id: 11, code: ‘code11’, name:‘名称11’},

      {id: 12, code: ‘code12’, name:‘名称12’},

      {id: 13, code: ‘code13’, name:‘名称13’},

      {id: 14, code: ‘code14’, name:‘名称14’},

      {id: 15, code: ‘code15’, name:‘名称15’},

      {id: 16, code: ‘code16’, name:‘名称16’},

      {id: 17, code: ‘code17’, name:‘名称17’},

      {id: 18, code: ‘code18’, name:‘名称18’},

      {id: 19, code: ‘code19’, name:‘名称19’},

      {id: 20, code: ‘code20’, name:‘名称20’},

      {id: 21, code: ‘code21’, name:‘名称21’},

      {id: 22, code: ‘code22’, name:‘名称22’},

      {id: 23, code: ‘code23’, name:‘名称23’},

      {id: 24, code: ‘code24’, name:‘名称24’},

    ],

    viewMode: ‘card’,

  },

  switchViewMode: function(e){

    let viewMode = e.target.dataset.viewMode

    this.setData({viewMode})

  }

})

注:scroll-view改为view似乎就不慢了。

能提供一个简单可复现的 DEMO 吗,谢谢

回到顶部