uniCloud入门学习
uniCloud是DCloud在阿里云和腾讯云的serverless服务上封装而成的。用熟悉的 js 就可以搞定整体的业务,加快开发速度。
官方文档:什么是uniCloud - uni-app官网 (dcloud.io)
环境准备
如果是新建项目,在新建时勾选启用 uniCloud.
如果是已有项目,右键创建 uniCloud 开发空间。
云服务空间创建完成后 关联云服务空间。
开发
可在 /uniCloud-aliyun/cloudfunctions 目录下新建云函数,对数据进行增删改查,也可以在页面中直接调用 API 实现。
查询
查询可使用 unicloud-db 标签,也可通过 API 接口实现。
unicloud-db 标签
unicloud-db 标签获取数据,就是在原有的 API 基础上对其进行了封装。
<unicloud-db ref="udb" collection="categories" field="name,sort,state,is_del,create_date,update_date" where="name==hello" page-data="replace" orderby="sort asc" :getcount="true" :page-size="options.pageSize" :page-current="options.pageCurrent" v-slot:default="{ data, pagination, loading, error, options }" :options="options" loadtime="manual" @load="onqueryload" > </unicloud-db> 复制代码
options: { pageSize, pageCurrent, filterData: {}, }, 复制代码
API查询
通过 get() API 可获取数据,where 可对数据进行过滤,field 是需要查询的数据库字段,orderBy 是排序字段以及排序方式。
uniCloud.database().collection('categories') .where('state==true') .field('name as text,_id as value,sort') .orderBy("sort asc") .get() .then(res => { console.log(res.result.data) }) .catch(err => { uni.showModal({ content: err.message || '请求服务失败', showCancel: false }); }) .finally(() => { uni.hideLoading(); }); 复制代码
新增
新增通过 add() API 实现。
uniCloud.database() .collection('categories') .add(value) .then(res => { }); 复制代码
修改
修改通过 update() API 实现。doc 可对主键 _id 进行搜索,之后调用 update() 对符合条件的数据进行修改。
uniCloud.database() .collection('categories') .doc(this.formDataId) .update(value) .then(res => { }); 复制代码
删除
通过 remove() API 实现数据的彻底删除。
uniCloud.database() .collection('categories') .doc(this.formDataId) .remove() .then(res => { }); 复制代码
云函数
如果对数据库的操作写在云函数中,在页面中可通过如下方式调用:
uni.showLoading({ mask: true }); uniCloud .callFunction({ name: 'categories', data: { type: 'mpweixin' } }) .then(res => { }) .catch(err => { uni.showModal({ content: err.message || '请求服务失败', showCancel: false }); }) .finally(() => { uni.hideLoading(); }); 复制代码
name 是云函数的文件夹名称,data 是需要传递的数据。
问题记录
联表查询
<unicloud-db ref="udb" collection="images,categories" field="category_id{name},image_url" :where="where" page-data="replace" :orderby="orderby" :getcount="true" :page-size="options.pageSize" :page-current="options.pageCurrent" v-slot:default="{ data, pagination, loading, error, options }" :options="options" loadtime="manual" @load="onqueryload" > </unicloud-db> 复制代码
如上:images 表的 category_id 和 categories表的 _id 相关联,当 category_id 作为查询条件,通过 where="category_id=123" 查询数据为空。可通过如下方式解决。
this.where = 'category_id._id=123' 复制代码
另附上项目小程序(幻彩头像:国庆春节头像生成)二维码:
作者:believe8301
链接:https://juejin.cn/post/7018434977943519268