UniApp 是一个使用 Vue.js 开发所有前端应用的框架,开发者编写一次代码,可发布到iOS、Android、H5以及各种小程序。如果你想在 UniApp 中操作云数据库,你可能需要使用云开发的功能。
以下是在 UniApp 中操作云数据库的一般步骤:
开通云开发环境:首先,你需要在微信开放平台开通云开发环境。这包括创建一个应用,并获取到你的应用ID。
 初始化云开发环境:在你的 UniApp 项目中,你需要初始化云开发环境。你可以在 manifest.json 文件中设置云开发环境。
 {
   "cloudfunctionRoot": "./cloudfunctions/",
   "cloudfunctionTemplateRoot": "./cloudfunction-templates/",
   "setting": {
     "cloudfunction": true,
     "cloudfunctionRoot": "./cloudfunctions/",
     "cloudfunctionTemplateRoot": "./cloudfunction-templates/",
     "setting": {
       "env": "env-xxxxxxxx", // 你的云开发环境ID
       "project": "project-xxxxxxxx", // 你的云开发项目ID
       "database": true // 开启云数据库
     }
   }
 }
编写云函数:你可以使用 JavaScript 编写云函数来操作数据库。
例如,你可以创建一个函数来增加一个新记录,或者查询一个记录。
 // 在 'cloudfunctions/example.js' 中
 export function addRecord(event, context, callback) {
   const db = context.db;
   const collection = db.collection('example'); // 你的集合名称
   const data = { name: event.name, age: event.age }; // 你要插入的数据
   collection.add({ data: data })
     .then(() => {
       callback(null, '成功'); // 回调成功的结果
     })
     .catch((err) => {
       callback(err); // 回调错误信息
     });
 }
调用云函数:你可以在你的 UniApp 项目中调用这个云函数。
例如,你可以在 Vue 组件中调用这个函数:
 // 在你的 Vue 组件中
 import cloud from '@/cloudfunctions'; // 导入你的云函数模块
export default {
   methods: {
     async addRecord() {
       const res = await cloud.callFunction('addRecord', { name: '张三', age: 20 }); // 调用你的云函数并传入参数
       console.log(res); // 打印回调结果
     }
   }
 }
查询数据库:你也可以编写一个云函数来查询数据库中的数据。
例如:
 // 在 'cloudfunctions/example.js' 中
 export function queryRecords(event, context, callback) {
   const db = context.db;
   const collection = db.collection('example'); // 你的集合名称
   collection.where('name', '==', event.name) // 查询条件,例如按名字查询
     .get() // 获取数据
     .then((res) => {
       callback(null, res); // 回调查询结果
     })
     .catch((err) => {
       callback(err); // 回调错误信息
     });
 }
调用查询函数:在你的 UniApp 项目中调用这个查询函数:
 // 在你的 Vue 组件中
 import cloud from '@/cloudfunctions'; // 导入你的云函数模块
export default {
   methods: {
     async queryRecords() {
       const res = await cloud.callFunction('queryRecords', { name: '张三' }); // 调用你的查询函数并传入参数
       console.log(res); // 打印查询结果
     }
   }
 }