微信小程序云开发具体文档:https://developers.weixin.qq.com/miniprogram/dev/framework/
页面元素:
<button type="primary" bindtap="getData">点击获取数据button>
<view>{
{dataObj.title}}view>
<view>{
{dataObj.author}}view>
<view>{
{dataObj.content}}view>
写方法:
data: {
dataObj:''
},
getData(){
//指定哪个数据库
// 查询方式一
db.collection('demolist').doc('e656fa635f729d1f00b10e0f70c9fe12').get({
success:res=>{
console.log(res)
this.setData({
dataObj:res.data
})
}
})
// 查询方式二:用到promise的回调函数
db.collection('demolist').get().then(res=>{
this.setData({
dataObj:res.data
})
})
// 查询方式三:一样可以拿到数组
db.collection('demolist').where({
author:'邢昀'
}).get().then(res=>{
console.log(res)
})
},
结果:
页面:
<button type="primary" bindtap="addData">插入一条数据button>
方法:可以不用写回调
addData(){
db.collection('demolist').add({
data:{
title:"ceshi",
author:"Van",
content:"还有一天到国庆"
}
})
},
结果:
页面:
注意:①提交方法绑定在form元素上
②给表单元素绑定name值,name值对应数据库的字段名
③提交按钮绑定事件
④重置绑定事件form-type=“reset”
<form bindsubmit="btnSub">
<input name="title" placeholder="请输入标题">input>
<input name="title" placeholder="请输入作者">input>
<textarea name="content" placeholder="请输入内容">textarea>
<button type="primary" form-type="submit">插入一条数据button>
<button form-type="reset">button>
form>
方法一直接赋值不推荐
btnSub(res){
var title=res.detail.value.title;
var author=res.detail.value.author;
var content=res.detail.value.content;
console.log(title,author,content)
},
方法二ES6结构赋值,value返回的是对象,{title,author,content}也是对象
btnSub(res){
var {
title,author,content}=res.detail.value
db.collection('demolist').add({
data:{
title:title,
author:author,
content:content
}
}).then(res=>{
console.log(res)
})
},
截图:
方法三对象赋值推荐
var resvalue=res.detail.value;
db.collection('demolist').add({
data:resvalue
}).then(res=>{
console.log(res)
})
操作dom元素:
<button type="primary" bindtap="updateData">更新一条记录button>
写js:用.doc指定到唯一字段_id从而修改数据
updateData(){
// 2.指定要更新的数据库
db.collection('demolist').doc('e373396c5f72ef3300b1078457e2ecc6').update({
data:{
author:'Van'
}
}).then(res=>{
console.log(res)
})
},
打印结果updated为1即成功修改数据:
截图:
注意:修改数据中.where需要配合云函数来使用
意思是你更新多少个字段,成功修改后就会留下你更新的字段删除其他原来的字段,反正就是不要用它啦。
delData(){
db.collection('demolist')
.doc('e373396c5f72ef3300b1078457e2ecc6')
.remove()
.then(res=>{
console.log(res)
})
},
删除数据操作通常由客户在客户端操作(云函数)
delData(){
db.collection('demolist')
.doc('e373396c5f72ef3300b1078457e2ecc6')
.remove()
.then(res=>{
console.log(res)
})
},
删除数据操作通常由客户在客户端操作(云函数)