学习unicloud一
准备工作
- 新建一个云空间并关联,最终效果
正式开始
- cloudfunctions右键创建云对象,代码就写在里面 index.obj.js中写上
module.exports = {
_before: function () { // 通用预处理器
},
say() {
return {
errCode: 0,
data: "hello, i'm uniCloud"
}
}
}
index.vue中使用,点击即可使用
<template>
<view class="content">
<button @click="callco">呼叫服务器</button>
</view>
</template>
<script>
export default {
data() {
return {
title: 'Hello'
}
},
onLoad() {
},
methods: {
async callco() {
const co1 = uniCloud.importObject("co1")
let res = await co1.say()
uni.showModal({
content: JSON.stringify(res),
showCancel:false
})
}
}
}
</script>
如果需要向云函数传递参数也很简单,直接写上参数 index.obj.js
module.exports = {
_before: function () { // 通用预处理器
},
say(test) {
return {
errCode: 0,
data: test
}
}
}
以上就是在本地使用云函数,如果在云端使用云函数,如果是单个云函数,直接在文件夹co1上上传部署,如果是多个云函数就在cloudfunctions邮件一次性上传所有,
最佳实践
- 开发期间连接本地云函数,最后完成部署到云端
怎么操作数据库
- 新建通讯录项目,和之前一样关联数据库
- 使用clientDB,选择云数据库,选择OpenDB的模版,也可以不选,这里自己创建contacts的表
- 把读表结构的读改成true
{
"bsonType": "object",
"required": [],
"permission": {
"read": true,
"create": false,
"update": false,
"delete": false
},
"properties": {
"_id": {
"description": "ID,系统自动生成"
}
}
}
- 手动添加两条记录
回到pages,编写几行代码即可展示数据
<template>
<view>
<unicloud-db v-slot:default="{data, loading, error, options}" collection="contacts">
<view v-if="error">{{error.message}}</view>
<view v-else>
{{data}}
</view>
</unicloud-db>
</view>
</template>
接下来继续完善下
- 安装uni-ui插件
- 写删除功能
<template>
<view>
<unicloud-db ref="udb"
v-slot:default="{data, loading, error, options}" collection="contacts">
<view v-if="error">{{error.message}}</view>
<view v-else>
<uni-list>
<uni-list-item v-for="item in data"
:key="item._id" :title="item.name" :note="item.phone"
@click.native="rmItem(item._id)"
link></uni-list-item>
</uni-list>
</view>
</unicloud-db>
</view>
</template>
<script>
export default {
name: 'list',
data() {
return {
}
},
methods: {
rmItem(id) {
console.log('fuck id', id)
this.$refs.udb.remove(id)
}
}
}
</script>
需要把dbschema给下载下来然后把delete和update改成true