本文實(shí)例為大家分享了微信小程序云開發(fā)實(shí)現(xiàn)數(shù)據(jù)添加、查詢和分頁,供大家參考,具體內(nèi)容如下
實(shí)現(xiàn)的效果

實(shí)現(xiàn)要點(diǎn)
WXML 不同類別數(shù)據(jù)的顯示
通過 if-elif-else 實(shí)現(xiàn),在wxml文件中通過 <block></block>渲染,因?yàn)樗鼉H僅是一個包裝元素,不會在頁面中做任何渲染,只接受控制屬性。也就是說可以通過屬性來控制頁面是否要渲染這部分的內(nèi)容,可以減少頁面渲染時間。
云開發(fā)數(shù)據(jù)的獲取
先開通云開發(fā)功能 ,參考官方文檔,然后在創(chuàng)建項(xiàng)目的時候勾選上 使用云開發(fā)模板(看個人吧,我直接使用后點(diǎn)擊項(xiàng)目中的 login)就可以獲取到用戶的oppenid,之后就可以使用云數(shù)據(jù)庫了。
云開發(fā)登錄:

云數(shù)據(jù)的獲取

/** * 生命周期函數(shù)--監(jiān)聽頁面加載 */ onLoad: function(options) { console.log('onload'); this.getData(this.data.page); }, /** * 獲取列表數(shù)據(jù) * */ getData: function(page) { var that = this; console.log("page--->" + page); const db = wx.cloud.database(); // 獲取總數(shù) db.collection('topic').count({ success: function(res) { that.data.totalCount = res.total; } }) // 獲取前十條 try { db.collection('topic') .where({ _openid: 'oSly***********vU1KwZE', // 填入當(dāng)前用戶 openid }) .limit(that.data.pageSize) // 限制返回?cái)?shù)量為 10 條 .orderBy('date', 'desc') .get({ success: function(res) { // res.data 是包含以上定義的兩條記錄的數(shù)組 // 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); } },云數(shù)據(jù)的添加
/** * 保存到發(fā)布集合中 */ saveDataToServer: function(event) { var that = this; const db = wx.cloud.database(); const topic = db.collection('topic') db.collection('topic').add({ // data 字段表示需新增的 JSON 數(shù)據(jù) 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 字段標(biāo)記剛創(chuàng)建的記錄的 id // 清空,然后重定向到首頁 console.log("success---->" + res) // 保存到發(fā)布?xì)v史 that.saveToHistoryServer(); // 清空數(shù)據(jù) that.data.content = ""; that.data.images = []; that.setData({ textContent: '', images: [], }) that.showTipAndSwitchTab(); }, complete: function(res) { console.log("complete---->" + res) } }) },
新聞熱點(diǎn)
疑難解答