首页 > 热点 > 微信 > 正文

微信小程序云开发实现数据添加、查询和分页

2024-07-22 01:18:26
字体:
来源:转载
供稿:网友

本文实例为大家分享了微信小程序云开发实现数据添加、查询和分页,供大家参考,具体内容如下

实现的效果

实现要点

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)  } }) },            
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表