1.初始化云开发环境
在小程序端开始使用云能力前,需先调用
wx.cloud.init方法完成云能力初始化
App({
onLaunch(){
wx.cloud.init({
env:'云开发环境ID'
})
}
})
2.云数据库
2.1创建一个数据表
点击添加记录
2.2获取数据
2.2.1获取全部数据
//es6(简洁)写法
Page({
onLoad() {
wx.cloud.database().collection('goods').get()
.then(res => {
console.log('请求成功',res);
}).catch(err => {
console.log('请求失败',err);
})
}
})
此时控制台输出的是请求成功,但是数据为0---->数据库的权限
我们将数据库的权限更改后,就能得到数据了
2.2.2where条件查询
Page({
data:{
list:[]
},
onLoad() {
wx.cloud.database().collection('goods')
.where({
name:'橘子'
}) .get()
.then(res => {
this.setData({
list:res.data
})
}).catch(err => {
console.log('请求失败',err);
})
}
})
2.2.3 doc查询单条数据
Page({
data:{
list:[]
},
onLoad() {
wx.cloud.database().collection('goods')
.doc('填入要查找的id') //单条数据查询返回的是对象
.get()
.then(res => {
console.log('成功',res.data);
}).catch(err => {
console.log('失败',err);
})
}
})
2.3数据渲染到页面上
//js
Page({
data:{
list:[]
},
onLoad() {
wx.cloud.database().collection('goods').get()
.then(res => {
this.setData({
list:res.data
})
}).catch(err => {
console.log('请求失败',err);
})
}
})
<!-- wxml -->
<view wx:for="{{list}}" wx:key="123">
<view>
名称:{{item.name}}
价格:{{item.price}}
</view>
</view>
2.4 add添加数据
Page({
onLoad(){
wx.cloud.database().collection('goods')
.add({
data:{
name:'草莓',
price: 20
}
})
.then(res => {
console.log('成功', res.data);
})
.catch(err => {
console.log('失败', err);
})
/*
如果添加失败
可以查看一下数据库的权限是否为可读
是的话就更改为:所有用户可读,仅创建者可读写即可
*/
}
})
2.5 update修改数据
update(){
wx.cloud.database().collection('goods')
.doc('要修改的数据的id')
.update({
data:{
price:25
}
})
.then(res => {
console.log('修改成功',res);
})
.catch(err => {
console.log('修改失败',err);
})
}
2.6 remove删除单条数据
remove(){
wx.cloud.database().collection('goods')
.doc('需要删除的数据id')
.remove()
.then(res => {
console.log('删除成功',res);
})
.catch(err => {
console.log('删除失败',err);
})
}
2.7 点击跳转详情(携带商品id)
//shopList
//wxml 使用 data-
data-id="{{item._id}}"
//js
detail(e){
wx.navigateTo({
url: '/pages/shops/shops?id='
+ e.currentTarget.dataset.id,
})
console.log('成功跳转详情页',
e.currentTarget.dataset.id);
}
})
//shops.js
Page({
data:{
good:{}
},
onLoad(options){
const id = options.id
wx.cloud.database().collection('goods')
.doc(id)
.get()
.then(res => {
this.setData({
good: res.data
})
})
.catch(err => {
console.log('失败', err);
})
}
})