连接数据库
Page({ onLoad: function (option) { //读取数据库 const that = this; const db = wx.cloud.database() if (!wx.cloud) { wx.redirectTo({ url: '../chooseLib/chooseLib', }) return } db.collection('test').get().then(res => { //test 为集合名 const list = res.data; //获取数据库的数据 this.setData({ list: list }) }) },});
插入新数据
// wxml<form bindsubmit='res'> //bindsubmit 绑定提交方法 res 为方法名 <view class="flex solid-bottom padding justify-end"> <button class='cu-btn line-red right' bindtap="toList" form-type='submit'>完成</button> </view> <view class="cu-form-group"> <textarea maxlength="-1" name="content" placeholder="多行文本输入框"></textarea> </view></form>// jsres: function (e) { const db = wx.cloud.database() db.collection('test').add({ data: { content: e.detail.value.content }, success: res => { // 在返回结果中会包含新创建的记录的 _id this.setData({ content: e.detail.value.content }) wx.showToast({ title: '新增记录成功', }) console.log('[数据库] [新增记录] 成功,记录 _id: ', res._id) }, fail: err => { wx.showToast({ icon: 'none', title: '新增记录失败' }) console.error('[数据库] [新增记录] 失败:', err) } })}
获取当前被点击元素的信息
// wsml<view bindtap="toAdd" data-content="{{item.content}}"></view>//js toAdd(event) { console.log(event.currentTarget.dataset.content); //当点被点击元素的数据 wx.navigateTo({ url: '../add/add?id=1' })}