新手上路,怎么把數據展示到前端是個很頭疼的問題,今天就來分享一下自己遇到的坑,先從雲開發后台中獲取集合中的所有記錄
//初始化數據庫 也可以寫在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>
至此終於出了這個數據調用,前端顯示的坑了