官方文档解读:
<!-- 更新记录 --> <view class="guide" wx:if="{{step === 5}}"> <text class="headline">更新记录</text> <text class="p">1. 打开 pages/databaseGuide/databaseGuide.js 文件,定位到 onCounterInc 和 onCounterDec 方法</text> <text class="p">2. 把注释掉的代码解除注释</text> <image class="code-image" src="../../images/code-db-inc-dec.png" mode="aspectFit"></image> <text class="p">3. 点击下方按钮更新计数器</text> <div class="counter"> <button class="minus" size="mini" type="default" bindtap="onCounterDec">-</button> <text class="p">{{count}}</text> <button class="plus" size="mini" type="default" bindtap="onCounterInc">+</button> </div> <div class="nav"> <button class="prev" size="mini" type="default" bindtap="prevStep">上一步</button> <button class="next" size="mini" type="default" bindtap="nextStep">下一步</button> </div> </view>
wxml:
<div class="counter"> <button class="minus" size="mini" type="default" bindtap="onCounterDec">-</button> <text class="p">{{count}}</text> <button class="plus" size="mini" type="default" bindtap="onCounterInc">+</button> </div>
js:
// pages/databaseGuide/databaseGuide.js const app = getApp() Page({ data: { step: 1, counterId: '', openid: '', count: null, queryResult: '', }, onLoad: function (options) { if (app.globalData.openid) { this.setData({ openid: app.globalData.openid }) } }, onCounterInc: function() { const db = wx.cloud.database() const newCount = this.data.count + 1 db.collection('counters').doc(this.data.counterId).update({ data: { count: newCount }, success: res => { this.setData({ count: newCount }) }, fail: err => { icon: 'none', console.error('[数据库] [更新记录] 失败:', err) } }) }, onCounterDec: function() { const db = wx.cloud.database() const newCount = this.data.count - 1 db.collection('counters').doc(this.data.counterId).update({ data: { count: newCount }, success: res => { this.setData({ count: newCount }) }, fail: err => { icon: 'none', console.error('[数据库] [更新记录] 失败:', err) } }) }, })