這篇文章主要爲大家詳細介紹了微信小程序雲開發實現數據添加、查詢和分頁,具有一定的參考價值,感興趣的小夥伴們可以參考一下
本文實例爲大家分享了微信小程序雲開發實現數據添加、查詢和分頁,供大家參考,具體內容如下
實現的效果
實現要點
WXML 不同類別數據的顯示
通過 if-elif-else 實現,在wxml文件中通過 <block></block>渲染,因爲它僅僅是一個包裝元素,不會在頁面中做任何渲染,只接受控制屬性。也就是說可以通過屬性來控制頁面是否要渲染這部分的內容,可以減少頁面渲染時間。
雲開發數據的獲取
先開通雲開發功能 ,參考官方文檔,然後在創建項目的時候勾選上 使用雲開發模板(看個人吧,我直接使用後點擊項目中的 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: '沒有更多數據了', }) } },
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持神馬文庫。