微信小程序template使用数组wx-for列表,onloade时setData()无效

问题描述:

把列表做成一个template,然后再index.wxml中使用,

<template name="videoSwiper">
  <scroll-view class="videos" scroll-x="true" scroll-with-animation="true">
    <view class="video" wx:for="{{videos2}}">
      <navigator>
        <image class="img" src="{{item.thumbnail}}"></image>
        <text class="title">{{item.title}}</text>
      </navigator>
    </view>
  </scroll-view>
</template>

index.js中的数据是我写的测试数据,放在video.js中,然后在onLoad的时候使用setData()的方法设置。
这时template中无法加载数据。

video.js如下

var videos = [
  {
    "id": 1,
    "title": "卡农",
    "thumbnail": "../../images/img1.jpg",
    "src": "http://wxsnsdy.tc.qq.com/105/20210/snsdyvideodownload?filekey=30280201010421301f0201690402534804102ca905ce620b1241b726bc41dcff44e00204012882540400&bizid=1023&hy=SH&fileparam=302c020101042530230204136ffd93020457e3c4ff02024ef202031e8d7f02030f42400204045a320a0201000400",
    "type": 1,
    "created": "2019-10-19 12:43:54",
    "createdBy": "2",
    "collectTimes": 289,
    "rank": 4
  },
  {
    "id": 2,
    "title": "梦中的婚礼",
    "thumbnail": "../../images/img2.jpg",
    "src": "http://wxsnsdy.tc.qq.com/105/20210/snsdyvideodownload?filekey=30280201010421301f0201690402534804102ca905ce620b1241b726bc41dcff44e00204012882540400&bizid=1023&hy=SH&fileparam=302c020101042530230204136ffd93020457e3c4ff02024ef202031e8d7f02030f42400204045a320a0201000400",
    "type": 2,
    "created": "2019-10-19 12:43:54",
    "createdBy": "2",
    "collectTimes": 289,
    "rank": 3
  }
]
module.exports = {
  dataList: videos
}

尝试1:
把video.js的数组直接写在index.js的data中,正常显示。

Page({
  data: {
	video: [。。。]
}
})

尝试2:
修改template,不用循环,只写单个元素的代码部分,然后在index.wxml中用列表,嵌套这个template,正常显示。

<navigator>
        <image class="img" src="{{item.thumbnail}}"></image>
        <text class="title">{{item.title}}</text>
      </navigator>

因为我的数据是要从数据库读取,所以只能在onload的时候设置,而不能一开始写在data中,弄了一晚上,放弃了,还是用简单的嵌套吧。

发布了21 篇原创文章 · 获赞 0 · 访问量 599

猜你喜欢

转载自blog.csdn.net/immocha/article/details/103749226