
读取数据在之前也有详细的写过案例了,现在用在项目里面,很容易就能理解了。
参考的读取api,请点击:https://developers.weixin.qq.com/miniprogram/dev/wxcloud/guide/database/read.html
1:初始化
实例和book方法
//云数据库初始化
const db = wx.cloud.database({});
const book = db.collection('books')
2:复制API这段代码获取多个记录的数据的方法,放在项目到onload方法之中


const db = wx.cloud.database({});
const cont = db.collection('books');
Page({
data: {},
onLoad: function(options) {
db.collection('books').get({
success(res) {
console.log(res.data)
}
})
},
})
3:打印在控制台

4:拿到res.data之后,要赋值给page实例里面的data
所以在data里面设置一个默认的空数组

5:创建一个变量来保存页面page示例中的this,方便后续使用
也可以使用箭头函数
来打印一下this,看是不是page示例
const db = wx.cloud.database({});
const cont = db.collection('books');
Page({
data: {
book_list:[]
},
onLoad: function(options) {
// 创建一个变量来保存页面page示例中的this, 方便后续使用
var _this=this;
db.collection('books').get({
success: res =>{
console.log(res.data);
console.log(this);
}
})
},
})

6:直接使用this来设置data

7:显示和布局:
使用组件库引入,可以省略自己写很多代码的样式,简单方便,当然也可以自己写。https://youzan.github.io/vant-weapp/#/card
因为数据不止一条,循环,所以要用到小程序框架的列表渲染
https://developers.weixin.qq.com/miniprogram/dev/framework/view/wxml/list.html
写好之后
wxml如下:
<text>私家书柜</text>
<view wx:for="{{book_list}}">
<van-card num="2" price="2.00" desc="描述信息" title="商品标题" />
</view>
8:先在js里面打印一条具体的数据,方便渲染的时候写出item.xxx的内容


9:小程序wxml界面
主要demo
wxml:
<view wx:for="{{book_list}}">
<van-card num="2"
price="{{item.price}}"
desc="{{item.author}}"
title="{{item.title}}"
thumb="{{item.image }}" />
</view>
js
const db = wx.cloud.database({});
const cont = db.collection('books');
Page({
data: {
book_list:[]
},
onLoad: function(options) {
// 创建一个变量来保存页面page示例中的this, 方便后续使用
var _this=this;
db.collection('books').get({
success: res =>{
console.log(res.data[0]);
this.setData({
book_list:res.data
})
}
})
},
})
ok,云数据库读取的数据显示在小程序端列表里.

附录:更多的云开发参考资料和视频
一个云开发的demo:https://github.com/LWJcoder/qiupihu
云开发图书私房柜:https://cloud.tencent.com/developer/edu/learn-100005-1244/3148
原文作者:祈澈姑娘 技术博客:https://www.jianshu.com/u/05f416aefbe1
90后前端妹子,爱编程,爱运营,爱折腾。坚持总结工作中遇到的技术问题,坚持记录工作中所所思所见,对于博客上面有不会的问题,可以加入qq群聊来问我:473819131。
网友评论