微信小程序零基础云开发-增删改查实例
第一步
新建项目
选择创建项目目录(目标文件夹为空)
填写AppID(来源:https://mp.weixin.qq.com/)
第二步
找到栏目 云开发 字样点击 选择基础版免费 创建云开发环境(稍等一到两分钟左右开通成功)
第三步
修改app.js文件配置
App({
onLaunch: function () {
if (!wx.cloud) {
console.error(‘请使用 2.2.3 或以上的基础库以使用云能力’)
} else {
wx.cloud.init({
env: ‘填写自己创建的环境ID’,
traceUser: true,
})
}
this.globalData = {}
}
})
编写集合添加数据方法
db.collection(“集合名”).add({
data: {
字段名: 变量名,
},
success: function (res) {
if (res.errMsg == “collection.add:ok”) {
wx.showModal({
title: ‘提示’,
content: ‘提交成功’,
showCancel: false,
success: function (res) {
wx.navigateBack({
delta: 2,
});
}
})
}
}
})
查询集合内所有数据
var db = wx.cloud.database();
db.collection(“集合名”).get({
success: function (res) {
if (res.data.length != 0) {
that.setData({
info: res.data
})
} else {
that.setData({
info: []
})
}
}
})
wxml代码
<view class='tr'>
<view class='th'>学号</view>
<view class='th'>姓名</view>
<view class='th'>年龄</view>
<view class='th'>性别</view>
<view class='th'>操作</view>
</view>
<view class='tr' wx:for="{{info}}" wx:key="key">
<view class='td'>{{item.student}}</view>
<view class='td'>{{item.name}}</view>
<view class='td'>{{item.age}}</view>
<view class='td'>{{item.gender}}</view>
<view class='td'>
<button bindtap='updateInfo' data-id="{{item._id}}">编辑</button>
<button bindtap='deleInfo' data-id="{{item._id}}">删除</button>
</view>
</view>
</view>
<button class="addbtn" bindtap="addClick">添加</button>
wxss代码
.table{
border: 1px solid #ccc;
width: 100%;
}
.tr{
width: 100%;
display: flex;
justify-content: space-between;
}
.th{
font-weight: 900;
color: blue;
}
.th,.td{
padding: 10px;
width: 100%;
text-align: center;
}
.td{
font-size: 14px;
height: 65px;
line-height: 65px;
border-top: 1px solid #ccc;
border-left: 1px solid #ccc;
}
button{
width: 60px;
height: 30px;
font-size: 14px;
text-align: center;
line-height: 30px;
margin-top: 2px;
}
.addbtn{background: #008000;color: #fff;width: 30%;}
编辑某条信息
通过_id 查询出集合内某一条信息数据
var db = wx.cloud.database();
db.collection("集合名").where({
_id: “变量名”
}).get({
success: function (res) {
}
})
db.collection("集合名").doc(字段名).update({
data: {
字段名: 变量名,
},
success: function (res) {
if (res.errMsg == "document.update:ok") {
//修改成功,返回一页
wx.showModal({
title: '提示',
content: '提交成功',
showCancel: false,
success: function (res) {
wx.navigateBack({
delta: 2,
});
}
})
}
}
})
删除集合内某一条数据
wx.showModal({
title: '是否确定删除所选内容?',
success: function (res) {
if (res.confirm) {
var db = wx.cloud.database();
db.collection('集合名').doc(id字段名).remove({
success: function (res) {
//删除成功,调用获取数据方法更新最新数据
//that.getdata();
},
fail: function (res) {
wx.showToast({
title: "删除失败",
icon: "none",
duration: 2000
})
}
})
}
}
})
参考资料
在学习和开发的过程中,我们主要会参考微信的开发文档。其原因是小程序太新了,相应的知识储备还不够丰富。虽然也可以找到一些开发方面的书籍,但是说实话,内容并不比微信本身的开发文档更详尽。
微信小程序开发交流群
1084039861
QQ搜索加入即可
群内不断更新微信小程序源码
全部提供免费下载
有不懂的小伙伴可以加群,群内有源码,随时提供。
小伙伴们可以在群内提问,随时解答。在线一对一远程辅导。