微信小程序云开发
微信小程序云开发使用腾讯提供的服务器,基于Serverless架构开发。测试号无云开发功能,因此在开发之前需要准备小程序的AppID一枚,完整源码位于GitHub 。
创建模板
使用小程序开发工具创建官方模板,删除index.js,index.wxml中的内容保留基础框架。
初始化
- 请注意在云开发中创建环境与数据库表:
- 初始化云开发需要在工程的app.js文件中编写wx.cloud.init函数:
1
2
3
4
5
6
7App({
onLaunch:function(){
wx.cloud.init({
env:'raincorn-lo6kz' //云开发的环境ID
})
}
}) 初始化数据库,在index.js中编写:
1
2
3
4const DB=wx.cloud.database().collection("list")
Page({
})- 注意当存在多个云环境时,云函数需要指定指定环境,同时需要在cloud.init()中指定。
数据库操作
增
- 在index.wxml中添加按钮:
1
2
3<input placeholder="输入名字" bindinput="addName"></input>
<input placeholder="输入年龄" bindinput="addAge"></input>
<button bindtap="addData" type="primary">添加数据</button> 在index.js中绑定按钮,编写数据库增加操作:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23const DB = wx.cloud.database().collection("list")
Page({
addName(event) {
name = event.detail.value
},
addAge(event) {
age = event.detail.value
},
addData() {
DB.add({
data: {
name: "hu",
age: 10
},
success(res) {
console.log("SUCCESS !", res)
},
fail(res) {
console.log("FAILED !", res)
}
})
}
})
删
- 在index.wxml中添加文本框与按钮
1
2<input placeholder="输入删除ID" bindinput="delDataInput"></input>
<button bindtap="delData" type="primary">删除数据</button> - 在index.js中配置后端
1
2
3
4
5
6
7
8
9
10
11
12
13delDataInput(event) {
id = event.detail.value
},
delData() {
DB.doc(id).remove({
success(res) {
console.log("数据库数据删除成功", res)
},
fail(res) {
console.log("数据库数据删除失败", res)
}
})
}
改
在index.wxml中配置输入
1
2
3<input placeholder="输入需要修改的ID" bindinput="udpDataInput"></input>
<input placeholder="输入需要修改的名字" bindinput="udpName"></input>
<button bindtap="udpData" type="primary">更新数据</button>在index.js中配置后端
1 | udpName(event) { |
查
1 | getData() { |
云函数
1 | // 云函数入口文件 |
1 | getsum() { |
云储存
- 前后端数据绑定
1
2<button bindtap="upload">上传图片</button>
<image src="{{imgUrl}}"></image> - 后端逻辑示例如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22data: {
imgUrl: ""
},
upload() {
wx.chooseImage({
success: chooseResult => {
wx.cloud.uploadFile({
cloudPath: new Date().getTime() + '.png', //使用时间戳唯一命名图片
filePath: chooseResult.tempFilePaths[0],
success: res => {
console.log('上传成功', res)
this.setData({
imgUrl: res.fileID
})
},
fail: res => {
console.log('上传失败', res)
}
})
}
})
}
本文标题:微信小程序云开发
文章作者:Raincorn
发布时间:2020-07-10
最后更新:2020-07-28
原始链接:https://blog.raincorn.top/2020/07/10/Wechat_CloudPrg/
版权声明:本文采用知识共享署名-非商业性使用 4.0 国际许可协议进行许可