前后端分离:前端请求云函数(书写逻辑),后端请求数据库(操作数据)
一、云函数初体验
# getData/index.js
const cloud = require('wx-server-sdk')
cloud.init()
const db=cloud.database();
exports.main = async (event, context) => {
return await db.collection("demoList").limit(event.num).get()
}
# pages/demo/demo2.js
Page({
data: {
},
onLoad: function (options) {
wx.cloud.callFunction({
name:"getData",
data:{
name:"张三",
age:20,
num:3,
}
}).then(res=>{
console.log("hbsad",res)
})
},
})
二、小案例
1.触底刷新+自增长
<!--pages/demo3/demo3.wxml-->
<view class="container" wx:for="{{demoList}}" wx:index="index" bindtap="addAge" data-id="{{item._id}}" data-index="{{index}}">
<view>{{index}}.我的名字是{{item.name}},年龄是{{item.age}}</view>
</view>
.container{
width: 100%;
height: 250rpx;
border: 1px solid gray;
}
Page({
data: {
demoList:[],
},
getData(num=5,page=0){
wx.cloud.callFunction({
name:'getData',
data:{
num:num,
page:page,
}
}).then(res=>{
var oldList=this.data.demoList
var newList=oldList.concat(res.result.data)
this.setData({
demoList:newList
})
})
},
addAge(e){
wx.showLoading({
title: '数据加载中...',
mask:true
})
var id=e.target.dataset.id;
var index=e.target.dataset.index;
wx.cloud.callFunction({
name:"addAge",
data:{
id:id,
}
}).then(res=>{
var newList=this.data.demoList
newList[index].age+=2;
this.setData({
demoList:newList
})
wx.hideLoading()
})
},
onLoad: function (options) {
this.getData()
},
onReachBottom: function () {
var page=this.data.demoList.length
this.getData(5,page)
},
})
const cloud = require('wx-server-sdk')
cloud.init()
const db=cloud.database();
exports.main = async (event, context) => {
return await db.collection("demoList").skip(event.page).limit(event.num).get()
}
const cloud = require('wx-server-sdk')
cloud.init()
const db=cloud.database()
const _=db.command;
exports.main = async (event, context) => {
var id=event.id;
return await db.collection("demoList").doc(id).update({
data:{
age:_.inc(2)
}
})
}
|