一个服务空间对应一整套独立的云开发资源,包括数据库、存储空间、云函数等资源。服务空间之间彼此隔离。
云函数是运行在云端的 JavaScript
代码,是基于 Node.js
的扩展。
云数据库是uniCloud
提供了一个 JSON 格式的文档型数据库。顾名思义,数据库中的每条记录都是一个 JSON 格式的文档
开发者使用uniCloud
的云存储,无需再像传统模式那样单独去购买存储空间、CDN映射、流量采购等;
index.vue
<template>
<view class="content">
<image class="logo" :src="imgPath"></image>
<view class="text-area">
<text class="title">{{title}}</text>
</view>
<button type="default" @click="get()">获取数据</button>
<button type="default" @click="uniSave()">云存储</button>
<button type="default" @click="mydelete()">删除存储</button>
</view>
</template>
<script>
export default {
data() {
return {
title: 'Hello',
imgPath: ''
}
},
onLoad() {
},
methods: {
get() {
// 云函数调用
uniCloud.callFunction({
// 云函数name
name: 'login',
// 向云函数传参
data: {
name: 'cookie'
},
success(res) {
console.log(res);
},
fail(err) {
console.log(err);
}
})
},
uniSave() {
// this指向会掉失 把this指向给self
let self = this
// 本地选择一张图片
uni.chooseFile({
// 限制文件个数为1
count: 1,
success(res) {
console.log(res);
// 云存储
uniCloud.uploadFile({
filePath: res.tempFilePaths[0],
cloudPath: 'a.jpg',
success(res) { // function的形式会导致this指向会掉失
console.log(res);
// this指向会掉失
self.imgPath = res.fileID
}
});
},
fail(err) {
console.log(err);
}
})
},
mydelete() {
uniCloud
// 删除云存储文件
.deleteFile({
fileList: ['504b399c-b74f-4468-b343-85a1c31a705a']
})
.then(res => {});
}
}
}
</script>
<style>
.content {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
}
.logo {
height: 200rpx;
width: 200rpx;
margin-top: 200rpx;
margin-left: auto;
margin-right: auto;
margin-bottom: 50rpx;
}
.text-area {
display: flex;
justify-content: center;
}
.title {
font-size: 36rpx;
color: #8f8f94;
}
</style>
云函数:login.js
'use strict';
// 获取数据库
const db = uniCloud.database()
exports.main = async (event, context) => {
// 获取表集合
const collection = await db.collection("user")
// 获取 where必须为对象 doc查询为字段值
let res = await collection.where({name: event.name}).get()
let res = await db.collection("user").doc(name).get()
// 新增数据
// let res = await collection.add({name: 'Ben'})
// 查询数据 where查询条件
// let res = await collection.where({name: 'Ben'})
// update更新数据
// let res = await collection.where({name: 'Ben'}).update({name: 'updateBen'})
// 删除数据
// let res = await collection.where({name: 'updateBen'}).remove()
console.log(JSON.stringify(res))
//event为客户端上传的参数
//返回数据给客户端
return {
code:200,
data:res.result
}
};