微信小程式~雲開發Demo 實現資料的新增、查詢和分頁實現
日更 15 天
實現的效果

在這裡插入圖片描述
實現要點
WXML 不同類別資料的顯示
通過 if-elif-else
實現,在 wxml
檔案中通過 <block></block>
渲染,因為它僅僅是一個包裝元素,不會在頁面中做任何渲染,只接受控制屬性。也就是說可以通過屬性來控制頁面是否要渲染這部分的內容,可以減少頁面渲染時間。
雲開發資料的獲取
先開通雲開發功能 ,參考 ofollow,noindex">官方文件 ,然後在建立專案的時候勾選上 使用雲開發模板(看個人吧,我直接使用後點擊專案中的 login
)就可以獲取到使用者的 oppenid
,之後就可以使用雲資料庫了。

在這裡插入圖片描述
雲開發登入:

在這裡插入圖片描述
- 雲資料的獲取
/** * 生命週期函式--監聽頁面載入 */ onLoad: function(options) { console.log('onload'); this.getData(this.data.page); }, /** * 獲取列表資料 * */ getData: function(page) { var that = this; console.log("page--->" + page); const db = wx.cloud.database(); // 獲取總數 db.collection('topic').count({ success: function(res) { that.data.totalCount = res.total; } }) // 獲取前十條 try { db.collection('topic') .where({ _openid: 'oSly***********vU1KwZE', // 填入當前使用者 openid }) .limit(that.data.pageSize) // 限制返回數量為 10 條 .orderBy('date', 'desc') .get({ success: function(res) { // res.data 是包含以上定義的兩條記錄的陣列 // console.log(res.data) that.data.topics = res.data; that.setData({ topics: that.data.topics, }) wx.hideNavigationBarLoading();//隱藏載入 wx.stopPullDownRefresh(); }, fail: function(event) { wx.hideNavigationBarLoading();//隱藏載入 wx.stopPullDownRefresh(); } }) } catch (e) { wx.hideNavigationBarLoading();//隱藏載入 wx.stopPullDownRefresh(); console.error(e); } },
- 雲資料的新增
/** * 儲存到釋出集合中 */ saveDataToServer: function(event) { var that = this; const db = wx.cloud.database(); const topic = db.collection('topic') db.collection('topic').add({ // data 欄位表示需新增的 JSON 資料 data: { content: that.data.content, date: new Date(), images: that.data.images, user: that.data.user, isLike: that.data.isLike, }, success: function(res) { // res 是一個物件,其中有 _id 欄位標記剛建立的記錄的 id // 清空,然後重定向到首頁 console.log("success---->" + res) // 儲存到釋出歷史 that.saveToHistoryServer(); // 清空資料 that.data.content = ""; that.data.images = []; that.setData({ textContent: '', images: [], }) that.showTipAndSwitchTab(); }, complete: function(res) { console.log("complete---->" + res) } }) },
-
雲資料的刪除
可檢視官放文件,這裡不貼程式碼了,有問題聯絡。
-
雲資料的更新
可檢視官放文件,這裡不貼程式碼了,有問題聯絡。
資料列表的分頁
主要就是定義一個臨時陣列存放載入上來的資料,然後通過傳遞給物件,最後傳遞到佈局中去。
/** * 頁面上拉觸底事件的處理函式 */ onReachBottom: function() { var that = this; var temp = []; // 獲取後面十條 if(this.data.topics.length < this.data.totalCount){ try { const db = wx.cloud.database(); db.collection('topic') .skip(5) .limit(that.data.pageSize) // 限制返回數量為 5 條 .orderBy('date', 'desc')// 排序 .get({ success: function (res) { // res.data 是包含以上定義的兩條記錄的陣列 if (res.data.length > 0) { for(var i=0; i < res.data.length; i++){ var tempTopic = res.data[i]; console.log(tempTopic); temp.push(tempTopic); } var totalTopic = {}; totalTopic =that.data.topics.concat(temp); console.log(totalTopic); that.setData({ topics: totalTopic, }) } else { wx.showToast({ title: '沒有更多資料了', }) } }, fail: function (event) { console.log("======" + event); } }) } catch (e) { console.error(e); } }else{ wx.showToast({ title: '沒有更多資料了', }) } },
完~,有問題可以聯絡
今天生病了,渾身沒勁,拿了我的之前在 CSDN 寫一篇文章過來分享,源地址在這: 微信小程式~雲開發Demo 實現資料的新增、查詢和分頁實現