小程序云开发怎么把数据从集合中展示在前端页面

新手上路,怎么把数据展示到前端是个很头疼的问题,今天就来分享一下自己遇到的坑,先从云开发后台中获取集合中的所有记录

//初始化数据库 也可以写在onload方法里面 看个人爱好
const db = wx.cloud.database();

Page({
  /**
   * 页面的初始数据
   */
  data: {
  },
  onLoad: function (options) {
    // 页面初始化 options为页面跳转所带来的参数
    //c_clear是集合名
    db.collection('c_clear').get({
      success: function (res) {
        // res.data 包含该集合下所有记录的数据  这里记录就几条 多的话使用limit()
        console.log(res.data);
      }
    })
  }
})

 

获取到数据之后 要使用this.setDate对数据进行赋值; 首先在date{ projects: [ ] } 定义一个空数组projects,然后通过this.setdate把获取的数据赋值给projects,这里有个坑就是this的指向问题,如果写在success这个方法里面的话,this指向的就是这个方法,我们要用到的是page上面的setDate,所以要在onload方法里面改变this的指向问题 var _this = this; 在success里面直接使用 _this.setDate({ projects: res.date})就可以了 

  onLoad: function (options) {
    var _this = this;//
    // 页面初始化 options为页面跳转所带来的参数
    db.collection('c_clear').get({
      success: function (res) {
        // res.data 包含该记录的数据
        _this.setData({  //这里注意不要直接使用 this
          projects: res.data
        })
      }
    })
  }

然后在前端通过 wx:for就可以调用了

    <view wx:for="{{projects}}" wx:for-item='item'>
      <image src="{{item.img_url}}"></image>
      <text class="cont_">{{item.contents}}</text>
      <text class="price">¥{{item.price}}</text>
      <text class="purchase">
        {{item.buy_num}}人已购买 
      </text>
    </view>

  至此终于出了这个数据调用,前端显示的坑了

原文地址:https://www.cnblogs.com/jzbs/p/12600892.html