跳到主要内容

UniApp 快速开始

准备工作

在开始之前,请确保您已完成以下准备:

  1. 开通云开发环境开通云开发环境
  2. 安装 Node.js下载 Node.js(建议 LTS 版本)

更多详情请参考:UniApp 完整文档

添加 CloudBase AI 开发插件

可选:如果你使用 AI 编程助手(如 Cursor、Claude Code、CodeBuddy 等)进行开发,建议先完成本步骤,让 AI 具备 CloudBase 开发能力。

复制 AI Prompt 粘贴到 AI IDE

在 AI 对话中输入:

帮我把 CloudBase 接好,按下面做:
1. 打开 https://docs.cloudbase.net/skill.md,按说明完成接入。
2. 接入完成后告诉我,并建议最相关的下一步。

查看 skill.md →

使用 Skills 开发

对 AI 说:

使用 CloudBase Skills:在 UniApp 应用中集成 CloudBase Web SDK,包括认证和数据库功能

Skills 使用文档 →

也可以手动安装 CloudBase Skills:

npx skills add tencentcloudbase/cloudbase-skills -y

安装 SDK

@cloudbase/js-sdk 配合 @cloudbase/adapter-uni-app 可以让您在 uni-app 项目中使用 JavaScript 访问 CloudBase 服务和资源。

npm

npm i @cloudbase/js-sdk @cloudbase/adapter-uni-app

yarn

yarn add @cloudbase/js-sdk @cloudbase/adapter-uni-app

pnpm

pnpm add @cloudbase/js-sdk @cloudbase/adapter-uni-app

初始化 SDK

新增如下代码到您的 uni-app 项目

./utils/cloudbase.js

import cloudbaseSDK from "@cloudbase/js-sdk";
import adapter from "@cloudbase/adapter-uni-app";

// 传入配置选项
const options = {
uni: uni // 传入 uni 对象,用于图形验证码功能
};

cloudbaseSDK.useAdapters(adapter, options);

const cloudbase = cloudbaseSDK.init({
// 环境 ID
env: "{%ENV_ID%}",
// 地域
region: "{%REGION%}",
// 匿名访问令牌
accessKey: "{%PUBLISHABLE_KEY%}"
});

export default cloudbase;

身份认证

使用 短信验证码注册 请先前往 身份认证/登录方式 开启 短信验证码

调用方式:

import cloudbase from "./utils/cloudbase";

const auth = cloudbase.auth();

// 发送验证码
const res = await auth.getVerification({ phone_number: phone });

// 验证验证码
const verifyRes = await auth.verify({
verification_id: verificationId,
verification_code: code
});

// 注册(如用户已存在则自动登录)
await auth.signUp({
phone_number: `+86 ${phone}`,
verification_code: code,
verification_token: verifyRes.verification_token,
name: `user_${phone.slice(-4)}`,
password: "admin@123"
});

完整示例:

<template>
<view>
<view>
<text>手机号:</text>
<input v-model="phone" placeholder="13800000000" />
</view>
<view>
<text>验证码:</text>
<input v-model="code" placeholder="验证码" />
<button :disabled="!phone" @click="sendCode">发送验证码</button>
</view>
<button :disabled="!verificationId || !code" @click="register">注册</button>
<text>{{ message }}</text
>
</view>
</template>

<script>
import cloudbase from "./utils/cloudbase";

export default {
data() {
return {
phone: "",
code: "",
verificationId: "",
message: ""
};
},
methods: {
// 发送验证码
async sendCode() {
try {
const auth = cloudbase.auth();
const res = await auth.getVerification({ phone_number: this.phone });
this.verificationId = res.verification_id;
this.message = "验证码已发送!";
} catch (error) {
this.message = "发送失败:" + error.message;
}
},

// 注册
async register() {
try {
const auth = cloudbase.auth();
// 验证验证码
const verifyRes = await auth.verify({
verification_id: this.verificationId,
verification_code: this.code
});
// 注册(如用户已存在则自动登录)
await auth.signUp({
phone_number: `+86 ${this.phone}`,
verification_code: this.code,
verification_token: verifyRes.verification_token,
name: `user_${this.phone.slice(-4)}`,
password: "admin@123"
});
this.message = "注册成功!";
} catch (error) {
this.message = "注册失败:" + error.message;
}
}
}
};
</script>

文档型数据库

调用方式:

import cloudbase from "./utils/cloudbase";

// 查询 {%TABLE_NAME%} 表前10条数据
const db = cloudbase.database();
const res = await db.collection("{%TABLE_NAME%}").limit(10).get();
console.log(res.data);

完整示例:

<template>
<view>
<button @click="getData">查询数据</button>
<view v-if="dataList.length > 0">
<view v-for="(item, index) in dataList" :key="index" class="data-item">
<text>{{ JSON.stringify(item) }}</text>
</view>
</view>
<text v-else>暂无数据</text>
</view>
</template>

<script>
import cloudbase from "./utils/cloudbase";

export default {
data() {
return {
dataList: []
};
},
methods: {
// 查询数据
async getData() {
try {
const db = cloudbase.database();
const res = await db.collection("{%TABLE_NAME%}").limit(10).get();

this.dataList = res.data;
uni.showToast({
title: "查询成功",
icon: "success"
});
} catch (error) {
uni.showToast({
title: "查询失败:" + error.message,
icon: "none"
});
}
}
}
};
</script>

云存储

调用方式:

import { cloudbase } from "./utils/cloudbase";

const res = await cloudbase.uploadFile({
cloudPath: `images/${Date.now()}-${file.name}`, // 上传至云端的路径
filePath: file
});
console.log(res.fileID);

完整示例:

<template>
<view>
<button @click="uploadFile">选择并上传图片</button>
<view v-if="fileId">
<text>上传成功!</text>
<text>文件ID: {{ fileId }}</text>
</view>
</view>
</template>

<script>
import cloudbase from "./utils/cloudbase";

export default {
data() {
return {
fileId: ""
};
},
methods: {
// 上传文件
async uploadFile() {
uni.chooseImage({
count: 1,
success: async chooseImageRes => {
try {
uni.showLoading({
title: "上传中..."
});

const tempFilePath = chooseImageRes.tempFilePaths[0];
const cloudPath = `images/${Date.now()}-${Math.random()}.png`;

const res = await cloudbase.uploadFile({
cloudPath: cloudPath,
filePath: tempFilePath
});

this.fileId = res.fileID;
uni.hideLoading();
uni.showToast({
title: "上传成功",
icon: "success"
});
} catch (error) {
uni.hideLoading();
uni.showToast({
title: "上传失败:" + error.message,
icon: "none"
});
}
}
});
}
}
};
</script>

云函数

调用方式:

import cloudbase from "./utils/cloudbase";

// 调用 {%FUNCTION_NAME%} 云函数
const res = await cloudbase.callFunction({
name: "{%FUNCTION_NAME%}",
data: {}
});
console.log(res.result);

完整示例:

<template>
<view>
<button @click="callFunction">调用云函数</button>
<view v-if="result">
<text>返回结果:</text>
<text>{{ JSON.stringify(result) }}</text>
</view>
</view>
</template>

<script>
import cloudbase from "./utils/cloudbase";

export default {
data() {
return {
result: null
};
},
methods: {
// 调用云函数
async callFunction() {
try {
const res = await cloudbase.callFunction({
name: "{%FUNCTION_NAME%}",
data: {}
});

this.result = res.result;
uni.showToast({
title: "调用成功",
icon: "success"
});
} catch (error) {
uni.showToast({
title: "调用失败:" + error.message,
icon: "none"
});
}
}
}
};
</script>

大模型

调用方式:

import { cloudbase } from "./utils/cloudbase";

const res = await cloudbase
.ai()
.createModel("{%AI_MODEL_NAME%}")
.streamText({
model: "{%AI_SUB_MODEL_NAME%}",
messages: [{ role: "user", content: "你好" }]
});

for await (let data of res.dataStream) {
// 如果有则打印思维链内容
const think = data?.choices?.[0]?.delta?.reasoning_content;
if (think) console.log(think);

// 打印生成文本内容
const text = data?.choices?.[0]?.delta?.content;
if (text) console.log(text);
}

完整示例:

<template>
<view>
<view>
<text>输入主题:</text>
<input v-model="input" placeholder="请输入主题,如:春天" />
</view>
<button :disabled="!input || isGenerating" @click="callAIModel">
生成内容
</button>
<view v-if="response">
<text>生成结果:</text>
<text>{{ response }}</text>
</view>
</view>
</template>

<script>
import cloudbase from "./utils/cloudbase";

export default {
data() {
return {
input: "",
response: "",
isGenerating: false
};
},
methods: {
// 调用大模型
async callAIModel() {
this.isGenerating = true;
this.response = "";

try {
// 确保已登录
const loginState = await cloudbase.auth().getLoginState();
if (!loginState) {
await cloudbase.auth().signInAnonymously();
}

uni.showLoading({
title: "生成中..."
});

const res = await cloudbase
.ai()
.createModel("<YOUR_AI_MODEL_NAME>")
.streamText({
model: "<YOUR_AI_SUB_MODEL_NAME>",
messages: [{ role: "user", content: this.input }]
});

for await (let str of res.textStream) {
this.response += str;
}

uni.hideLoading();
uni.showToast({
title: "生成完成",
icon: "success"
});
} catch (err) {
uni.hideLoading();
uni.showToast({
title: "生成失败:" + err.message,
icon: "none"
});
} finally {
this.isGenerating = false;
}
}
}
};
</script>