小程序云开发出来之后,小程序开发人员也要慢慢的接触后端对数据的增删改查了。下面就给大家提供一个案例吧。
这里我把新增和修改放在了一个页面
显示页面index.wxml
查看wx : if=' { { books } } ' class=' container ' view class=' title ' text图书列表/text/view view class=' label ' text书名/text文本作者/text文本价格/text文本操作/text/view block wx : for=' { { books } } ' wx : key=' ' view class=' content ' text { { item。name } }/text text { { item。作者} }/文本文本{ { item。price } }/text button class=' del ' data-id=' { { item ._id}}' bindtap='onDel '删除/button button class=' update ' data-id=' { { item ._id}}' bindtap='onUpdate '修改/button/view/block/view view wx : else=' { { books } } ' class=' none ' text暂时没有图书!/text/viewview class='add '按钮bindtap='goSet '添加图书/button/viewindex.js
//页数/索引/索引。js页面({/* * *页面的初始数据*/data: { books:[] },/** *生命周期函数-监听页面加载*/onLoad:函数(选项){ const db=wx。云。数据库()。db。收藏(书).get({ success : RES={ this。setdata({ books : RES . data })},fail : err={ wx。显示吐司({图标: '无',标题: '查询记录失败,})})),goset : FuncTion(){ wx。navigateto({ URL : './set/set ',}) },ondel :函数(e){ let id=e . CurrentTarget。数据集。id const db=wx。云。database();db.collection(书籍).文档(身份证).移除({ success : RES={ wx。ShowToast({ title : ')删除成功,}) this.onLoad()//删除成功重新加载},fail : err={ wx。ShowToast({ title : '删除失败,})})控制台。log(id)},onupdates :函数(e){ let id=e . currenttarget。数据集。id wx。导航到({ URL : './set/set?id=' id,}) })添加和修改共用set.wxml
!-页面/集合/集合。wxml-view class=' container '表单绑定提交=' confirm ' view class=' input-container '标签书名:/标签输入style=' display : none ' data-value=' { { id } } ' name=' id ' value=' { { book ._ id } } '/input input data-value=' { { name } } ' name=' name ' value=' { { book。name } } '/input/view view view class=' input-container '标签作者:/label输入数据-值=' { { author } } '名称=' author '值=' { { book。author } } '/input/view view view class=' input-container '标签价格:/标签输入数据-值=“{ { price } }”名称='价格'值=' { { book。price } } '/input/view view class=' confirm '按钮表单-类型='提交'保存/button /view /form/viewset.js
//pages/set/set.jsPage({ /** *页面的初始数据*/data: { book:[] },/** *生命周期函数-监听页面加载*/onLoad:函数(选项){ if(options。id){ const db=wx。云。database();db.collection(书籍).其中({ _id:options.id }).get({ success : RES={ this。setdata({ book : RES . data[0]//返回的是一个数组,取第一个}) },失败: err={ console。log(err)} })}),确认:函数(e){ const db=wx。云。database()//打开数据库连接让书=e .细节。值if(book。id==' '){//id等于空是新增数据this.add(db,book) //新增记录}else{ this.update(db,book) //修改记录} },add:函数(db,book) { db.collection('books ').添加({ data: { name: book.name,author: book.author,price : parseFloat(book。价格)},成功3360 RES={ wx。显示吐司({ title : '新增记录成功,}) wx.navigateTo({ url: './index/index ',}) },fail : err={ wx。showtoast({ title : '新增失败,})})}),更新:函数(db,book) { db.collection('books ').文件(book.id).更新({ data : { name :图书。姓名,作者: book.author,价格: parseFloat(book。价格)},成功3360 RES={ wx。显示吐司({ title : '修改记录成功,}) wx.navigateTo({ url: './index/index ',}) },fail : err={ wx。showtoast({ title : '修改失败', }) } }) } })云开发后台数据,需要手动添加书集合:
微信
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。