uniapp云函数的使用

218 阅读2分钟

dcloud官网去开通空间,腾讯是收费的,阿里和支付宝都有免费的提供,用来练习免费的就够了。

Hbuilder新建项目时选择绑定已存在的空间,或在已存在的项目中右键绑定空间

image.png

创建完之后你的项目目录下会多出一个uniClold文件夹

image.png

下边开始新建数据库表结构 在database文件夹上右键选择新建schema,选择默认模板,新建的文件是这个样子的

// 文档教程: https://uniapp.dcloud.net.cn/uniCloud/schema
{
	"bsonType": "object",
	"required": [],
	"permission": {
		"read": false,
		"create": false,
		"update": false,
		"delete": false
	},
	"properties": {
		"_id": {
			"description": "ID,系统自动生成"
		}
	}
}

下边给该表添加title,type字段,都是string类型,bsonType表示字段类型

// 文档教程: https://uniapp.dcloud.net.cn/uniCloud/schema
{
	"bsonType": "object",
	"required": [],
	"permission": {
		"read": false,
		"create": false,
		"update": false,
		"delete": false
	},
	"properties": {
		"_id": {
			"description": "ID,系统自动生成"
		},
		"title": {
			"bsonType": "string",
			"description": "我是标题"
		},
                "type": {
			"bsonType": "string",
			"description": "我是类型"
		}
	}
}

选择你刚建的这个文件,右键点击上传,成功后表示该表已新建成功了,可以去后台看下已经存在了

下边新建一个云函数,在cloudfunctions上右键选择新建云函数,让我们插入一条数据到数据库

'use strict';
const db = uniCloud.database();
exports.main = async (event, context) => {
	//event为客户端上传的参数
	console.log('event : ', event)
	const {
		type,
		title
	} = event;

	// 准备要插入的数据
	const dataToInsert = {
		type: type,
		title: title,
		// 可以添加其他字段
	};
console.log('dataToInsert : ', dataToInsert)
	// 插入到script_list数据库中
	try {
		const result = await db.collection('script_list').add(dataToInsert);
		return {
			code: 0,
			message: '数据插入成功',
			data: result
		};
	} catch (error) {
		return {
			code: -1,
			message: '数据插入失败',
			error: error
		};
	}
	//返回数据给客户端
	return event
};

查询数据

'use strict';
const db = uniCloud.database();
exports.main = async (event, context) => {
	//event为客户端上传的参数
	console.log('event : ', event)
	const {
		type
	} = event;

	// 根据type查询script_list中的数据
	try {
		const result = await db.collection('script_list').where({type}).get()
		return {
			code: 0,
			message: '查询成功',
			data: result.data // 返回查询结果
		};
	} catch (error) {
		return {
			code: -1,
			message: '查询失败132',
			error: error
		};
	}
};

接下来uniapp中调用云函数即可

···
methods: {
    async addScript() {
      try {
            const result = await uniCloud.callFunction({
              name: 'getlist', // 替换为你的云函数名称
              data: {
                    type:'fuben'
              }
            });
            console.log('数据插入结果:', result);
      } catch (error) {
            console.error('调用云函数失败', error);
      }
    },
···

name换成你的函数名称,data是要传递的数据

至此云函数就可以简单的使用了,还是比较简单的。