在项目的uniCloud---cloudfunctions文件夹上右键,新建云函数/云对象
单选框选择"云对象", 命名,创建
云对象代码
const db = uniCloud.database()
module.exports = {
_before: function() {},
// 定义云对象异步函数
async get(num) {
return await db.collection("users").orderBy("_id","desc").limit(num).get()
},
// 函数普通写法箭头写法都行
add:async (dataObj)=>{
await db.collection("users").add(dataObj)
}
}
前端页面代码
<template>
<view class="content">
<view v-for="item in dataList" :key="item._id">
{{item.name}}---{{item.gender}}---{{item.age}}
</view>
</view>
</template>
<script>
// 引入云对象
const cloudObj1 = uniCloud.importObject("test_cloudObj1")
export default {
data() {
return {
title: 'Hello',
dataList: [],
dataNum: 5
}
},
onLoad() {
this.getData();
},
methods: {
getData() {
cloudObj1.add({
name: "zhang3",
gender: "男",
age: 17
})
// 云对象获取数据
cloudObj1.get(this.dataNum).then(res => {
console.log(res);
this.dataList = res.data
}, err => {
console.log(err.message);
})
return;
// 云函数获取数据
uniCloud.callFunction({
name: "test_cloudFun1",
data: {
num: this.dataNum
},
success: (res) => {
console.log("success@@@@", res);
this.dataList = res.result.data;
},
fail: (err) => {
console.log("fail@@@@", err.message);
}
})
}
}
}
</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>