一、添加操作
1.前端构造输入框绑定onInput方法进行监听。
<view>
<input
bindinput="onInput"
value="{{ inputValue }}"
placeholder="请输入内容"
type="text" />
</view>
2.通过onInput监听输入框的变化并在提交时将值传递给inputValue 。
onInput: function (e) {
this.setData({
inputValue: e.detail.value
});
},
3.js调用云函数,并将值传递到云函数。
addinfo: function () {
const inputValue = this.data.inputValue;
wx.cloud.callFunction({
name: "addinfo",
data: {
phone: inputValue
},
success(res) {
console.log("添加成功:", res);
wx.showToast({
icon: 'success',
title: '添加成功',
});
},
fail(res) {
console.log("添加失败:", res);
}
});
},
4.云函数接受js传递过来的值完成数据库的操作即可。
exports.main = async (event, context) => {
return db.collection("test").add({
data:{
phone:event.phone
}
})
}
二、查找操作
1.js通过wx.cloud.callFunction方法调用云函数,并在每个节点设置控制台输出以便排错。
getdata: function () {
wx.cloud.callFunction({
name: "getdata",
success: res => {
console.log(res);
if (res.result) {
this.setData({
dataobj: res.result.data
});
} else {
console.log("没有数据返回");
}
},
fail: err => {
console.log("调用失败", err);
}
});
},
2.查询test集合中所有的数据,在控制台可以看到返回的是一个数组类型,且是result数据,所以js中用res.result.data,在wxml中使用wx:for与item将数据展示到前端。
exports.main = async (event, context) => {
const res = await db.collection("test").get()
return res.data
}
三、删除操作
1.js文件将要删除数据的id传到云函数,云函数调用remove方法即可。
delInfo:function(){
wx.cloud.callFunction({
name: "delInfo",
data: {
id: "11ad502367ab15f80277ec353a8ba4fe"
},
success(res) {
console.log("删除成功:", res);
wx.showToast({
icon: 'success',
title: '删除成功',
});
},
fail(res) {
console.log("删除失败:", res);
wx.showToast({
icon: 'none',
title: '删除失败',
});
}
});
}
exports.main = async (event, context) => {
phone = event.id
return db.collection("test").doc(id).remove()
}
四、更新操作
同样的使用js传递参数到云函数,云函数使用update方法实现。
updateInfo:function() {
wx.cloud.callFunction({
name:"updateInfo",
data:{
id:"e33be08d67aac1c8027220bb47c3679b",
phone:"12345678"
},
success(res) {
console.log(res)
wx.showToast({
title: '更新成功!',
})
},
fail(res){
console.log(res)
wx.showToast({
title: 'fail',
})
}
})
}
exports.main = async (event, context) => {
id = event.id
phone = event.phone
return db.collection("test").doc(id).update({
data:{
phone:phone
}
})
}