UniApp 快速开始
- AI 快速开始
- 完整开发指引
准备工作
在开始之前,请确保您已完成以下准备:
- 开通云开发环境:开通云开发环境
- 安装 Node.js:下载 Node.js(建议 LTS 版本)
Client
配置你的 AI 工具以连接 CloudBase 能力 支持本地与托管两种连接方式,详见 连接方式。
步骤 1:安装 / 配置 CloudBase
步骤 2:和 AI 对话
在 AI 对话中依次输入以下内容:
prompt
安装 CloudBase Skills:命令 npx skills add tencentcloudbase/cloudbase-skills -y使用 CloudBase Skills: 使用 CloudBase Skills:在 UniApp 应用中集成 CloudBase Web SDK,包括认证和数据库功能准备工作
在开始之前,请确保您已完成以下准备:
- 开通云开发环境:开通云开发环境
- 安装 Node.js:下载 Node.js(建议 LTS 版本)
更多详情请参考:UniApp 完整文档
安装 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;
身份认证
- 短信验证码注册
- 邮箱验证码注册
- 账号密码登录
- 短信验证码登录
- 邮箱验证码登录
- 小程序手机号登录
- 微信 OpenID 登录
使用 短信验证码注册 请先前往 身份认证/登录方式 开启 短信验证码
调用方式:
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";
const auth = cloudbase.auth();
// 发送验证码
const res = await auth.getVerification({ email });
// 验证验证码
const verifyRes = await auth.verify({
verification_id: verificationId,
verification_code: code
});
// 注册(如用户已存在则自动登录)
await auth.signUp({
email,
verification_code: code,
verification_token: verifyRes.verification_token,
name: `user_${email.slice(-4)}`,
password: "admin@123"
});
完整示例:
<template>
<view>
<view>
<text>邮箱:</text>
<input v-model="email" placeholder="example@email.com" />
</view>
<view>
<text>验证码:</text>
<input v-model="code" placeholder="验证码" />
<button :disabled="!email" @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 {
email: "",
code: "",
verificationId: "",
message: ""
};
},
methods: {
// 发送验证码
async sendCode() {
try {
const auth = cloudbase.auth();
const res = await auth.getVerification({ email: this.email });
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({
email: this.email,
verification_code: this.code,
verification_token: verifyRes.verification_token,
name: `user_${this.email.slice(-4)}`,
password: "admin@123"
});
this.message = "注册成功!";
} catch (error) {
this.message = "注册失败:" + error.message;
}
}
}
};
</script>
使用 账号密码登录 请先前往 身份认证/登录方式 开启 用户名密码登录
调用方式:
import cloudbase from "./utils/cloudbase";
const auth = cloudbase.auth();
await auth.signIn({
username, // 可以是用户名、手机号或邮箱
password
});
完整示例:
<template>
<view>
<view>
<text>账号:</text>
<input v-model="username" placeholder="用户名/手机号/邮箱" />
<text>注:手机号登录请添加区号 +86</text>
</view>
<view>
<text>密码:</text>
<input type="password" v-model="password" placeholder="请输入密码" />
</view>
<button :disabled="!username || !password" @click="login">登录</button>
<text>{{ message }}</text
>
</view>
</template>
<script>
import cloudbase from "./utils/cloudbase";
export default {
data() {
return {
username: "",
password: "",
message: ""
};
},
methods: {
// 登录
async login() {
try {
const auth = cloudbase.auth();
await auth.signIn({
username: this.username, // 可以是用户名、手机号或邮箱
password: this.password
});
this.message = "登录成功!";
} catch (error) {
this.message = "登录失败:" + error.message;
}
}
}
};
</script>
使用 短信验证码登录 请先前往 身份认证/登录方式 开启 短信验证码登录
调用方式:
import cloudbase from "./utils/cloudbase";
const auth = cloudbase.auth();
// 发送验证码
const res = await auth.getVerification({ phone_number: `+86 ${phone}` });
// 登录
await auth.signInWithSms({
verificationInfo: res,
verificationCode: code,
phoneNum: `+86 ${phone}`
});
完整示例:
<template>
<view>
<view>
<text>手机号:</text>
<input v-model="phone" placeholder="13800000000" />
</view>
<view>
<text>验证码:</text>
<input v-model="code" placeholder="验证码" />
<button @click="sendCode" :disabled="!phone">发送验证码</button>
</view>
<button @click="login" :disabled="!verificationInfo || !code">登录</button>
<text>{{ message }}</text
>
</view>
</template>
<script>
import cloudbase from "./utils/cloudbase";
export default {
data() {
return {
phone: "",
code: "",
verificationInfo: null,
message: ""
};
},
methods: {
// 发送验证码
async sendCode() {
try {
const auth = cloudbase.auth();
const res = await auth.getVerification({
phone_number: `+86 ${this.phone}`
});
this.verificationInfo = res;
this.message = "验证码已发送!";
} catch (error) {
this.message = "发送失败:" + error.message;
}
},
// 登录
async login() {
try {
const auth = cloudbase.auth();
await auth.signInWithSms({
verificationInfo: this.verificationInfo,
verificationCode: this.code,
phoneNum: `+86 ${this.phone}`
});
this.message = "登录成功!";
} catch (error) {
this.message = "登录失败:" + error.message;
}
}
}
};
</script>
使用 邮箱验证码登录 请先前往 身份认证/登录方式 开启 邮箱验证码
调用方式:
import cloudbase from "./utils/cloudbase";
const auth = cloudbase.auth();
// 发送验证码
const res = await auth.getVerification({ email });
// 登录
await auth.signInWithEmail({
verificationInfo: res,
verificationCode: code,
email
});
完整示例:
<template>
<view>
<view>
<text>邮箱:</text>
<input v-model="email" placeholder="example@email.com" />
</view>
<view>
<text>验证码:</text>
<input v-model="code" placeholder="验证码" />
<button @click="sendCode" :disabled="!email">发送验证码</button>
</view>
<button @click="login" :disabled="!verificationInfo || !code">登录</button>
<text>{{ message }}</text
>
</view>
</template>
<script>
import cloudbase from "./utils/cloudbase";
export default {
data() {
return {
email: "",
code: "",
verificationInfo: null,
message: ""
};
},
methods: {
// 发送验证码
async sendCode() {
try {
const auth = cloudbase.auth();
const res = await auth.getVerification({ email: this.email });
this.verificationInfo = res;
this.message = "验证码已发送!";
} catch (error) {
this.message = "发送失败:" + error.message;
}
},
// 登录
async login() {
try {
const auth = cloudbase.auth();
await auth.signInWithEmail({
verificationInfo: this.verificationInfo,
verificationCode: this.code,
email: this.email
});
this.message = "登录成功!";
} catch (error) {
this.message = "登录失败:" + error.message;
}
}
}
};
</script>
调用方式:
import cloudbase from "./utils/cloudbase";
const auth = cloudbase.auth();
// 手机号授权登录
const loginResult = await auth.signInWithPhoneAuth(code);
完整示例:
<template>
<view>
<button open-type="getPhoneNumber" @getphonenumber="handleGetPhoneNumber">
微信小程序登录
</button>
</view>
</template>
<script>
import cloudbase from './utils/cloudbase';
export default {
data() {
return {}
},
methods: {
async handleGetPhoneNumber(event) {
if(!event.detail.code) {
console.error('获取手机号失败:', event.detail.errMsg);
uni.showToast({
title: '获取手机号失败',
icon: 'none'
});
return
}
console.log('获取到动态令牌(code):', event.detail.code);
uni.showLoading({
title: '登录中...'
});
try {
// 手机号授权登录
const auth = cloudbase.auth();
const loginResult = await auth.signInWithPhoneAuth( event.detail.code );
console.log('手机号授权登录结果:', loginResult);
uni.hideLoading();
uni.showToast({
title: '登录成功',
icon: 'success'
});
} catch (error: any) {
// 处理登录失败
console.error('手机号授权登录失败:', error);
uni.showToast({
title: error.message || '登录失败',
icon: 'none'
});
} finally {
uni.hideLoading();
}
}
}
}
</script>
调用方式:
import cloudbase from "./utils/cloudbase";
const auth = cloudbase.auth();
// 微信 OpenID 登录
const loginResult = await auth.signInWithOpenId();
完整示例:
<template>
<view>
<button @click="openIdLogin">微信小程序登录</button>
</view>
</template>
<script>
import cloudbase from './utils/cloudbase';
export default {
data() {
return {}
},
methods: {
async openIdLogin() {
uni.showLoading({
title: '正在登录...'
});
try {
const auth = cloudbase.auth();
const loginResult = await auth.signInWithOpenId();
console.log('微信 OpenID 登录成功:', loginResult);
uni.hideLoading();
uni.showToast({
title: '登录成功',
icon: 'success'
});
} catch (error: any) {
uni.hideLoading();
console.error('微信 OpenID 登录失败:', error);
uni.showToast({
title: error.message || '登录失败,请重试',
icon: 'none'
});
}
}
}
}
</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";
// 新增 {%TABLE_NAME%} 表数据
const db = cloudbase.database();
const res = await db.collection("{%TABLE_NAME%}").add({ title: "示例标题" });
console.log(`新增成功! id: ${res.id}`);
完整示例:
<template>
<view>
<view>
<text>标题:</text>
<input v-model="title" placeholder="请输入标题" />
</view>
<button :disabled="!title" @click="addData">新增数据</button>
</view>
</template>
<script>
import cloudbase from "./utils/cloudbase";
export default {
data() {
return {
title: ""
};
},
methods: {
// 新增数据
async addData() {
try {
const db = cloudbase.database();
const res = await db
.collection("{%TABLE_NAME%}")
.add({ title: this.title });
uni.showToast({
title: `新增成功! id: ${res.id}`,
icon: "success"
});
this.title = "";
} catch (error) {
uni.showToast({
title: "新增失败:" + error.message,
icon: "none"
});
}
}
}
};
</script>
调用方式:
import cloudbase from "./utils/cloudbase";
// 更新 {%TABLE_NAME%} 表中 id 为指定值的数据
const db = cloudbase.database();
await db
.collection("{%TABLE_NAME%}")
.doc("<数据id>")
.update({ title: "新标题" });
完整示例:
<template>
<view>
<view>
<text>数据ID:</text>
<input v-model="dataId" placeholder="请输入数据ID" />
</view>
<view>
<text>新标题:</text>
<input v-model="newTitle" placeholder="请输入新标题" />
</view>
<button :disabled="!dataId || !newTitle" @click="updateData">
更新数据
</button>
</view>
</template>
<script>
import cloudbase from "./utils/cloudbase";
export default {
data() {
return {
dataId: "",
newTitle: ""
};
},
methods: {
// 更新数据
async updateData() {
try {
const db = cloudbase.database();
await db
.collection("{%TABLE_NAME%}")
.doc(this.dataId)
.update({ title: this.newTitle });
uni.showToast({
title: "更新成功",
icon: "success"
});
this.dataId = "";
this.newTitle = "";
} catch (error) {
uni.showToast({
title: "更新失败:" + error.message,
icon: "none"
});
}
}
}
};
</script>
调用方式:
import cloudbase from "./utils/cloudbase";
// 删除 {%TABLE_NAME%} 表中 id 为指定值的数据
const db = cloudbase.database();
await db.collection("{%TABLE_NAME%}").doc("<数据id>").remove();
完整示例:
<template>
<view>
<view>
<text>数据ID:</text>
<input v-model="dataId" placeholder="请输入要删除的数据ID" />
</view>
<button :disabled="!dataId" @click="deleteData">删除数据</button>
</view>
</template>
<script>
import cloudbase from "./utils/cloudbase";
export default {
data() {
return {
dataId: ""
};
},
methods: {
// 删除数据
async deleteData() {
try {
const db = cloudbase.database();
await db.collection("{%TABLE_NAME%}").doc(this.dataId).remove();
uni.showToast({
title: "删除成功",
icon: "success"
});
this.dataId = "";
} 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";
const res = await cloudbase.getTempFileURL({
fileList: ["cloud://xxx.png"] // 文件 fileID 列表
});
console.log(res.fileList[0].tempFileURL);
完整示例:
<template>
<view>
<view>
<text>文件ID:</text>
<input v-model="fileId" placeholder="请输入文件ID (cloud://xxx.png)" />
</view>
<button :disabled="!fileId" @click="getFileUrl">获取文件链接</button>
<view v-if="fileUrl">
<text>文件链接:</text>
<text>{{ fileUrl }}</text>
<image :src="fileUrl" mode="aspectFit"></image>
</view>
</view>
</template>
<script>
import cloudbase from "./utils/cloudbase";
export default {
data() {
return {
fileId: "",
fileUrl: ""
};
},
methods: {
// 获取文件链接
async getFileUrl() {
try {
const res = await cloudbase.getTempFileURL({
fileList: [this.fileId]
});
this.fileUrl = res.fileList[0].tempFileURL;
uni.showToast({
title: "获取成功",
icon: "success"
});
} catch (error) {
uni.showToast({
title: "获取失败:" + error.message,
icon: "none"
});
}
}
}
};
</script>
调用方式:
import { cloudbase } from "./utils/cloudbase";
await cloudbase.downloadFile({
fileID: "cloud://xxx.png" // 文件 fileID
});
完整示例:
<template>
<view>
<view>
<text>文件ID:</text>
<input v-model="fileId" placeholder="请输入文件ID (cloud://xxx.png)" />
</view>
<button :disabled="!fileId" @click="downloadFile">下载文件</button>
<view v-if="localPath">
<text>下载成功!</text>
<text>本地路径: {{ localPath }}</text>
</view>
</view>
</template>
<script>
import cloudbase from "./utils/cloudbase";
export default {
data() {
return {
fileId: "",
localPath: ""
};
},
methods: {
// 下载文件
async downloadFile() {
try {
uni.showLoading({
title: "下载中..."
});
const res = await cloudbase.downloadFile({
fileID: this.fileId
});
this.localPath = res.tempFilePath;
uni.hideLoading();
uni.showToast({
title: "下载成功",
icon: "success"
});
} catch (error) {
uni.hideLoading();
uni.showToast({
title: "下载失败:" + error.message,
icon: "none"
});
}
}
}
};
</script>
调用方式:
import { cloudbase } from "./utils/cloudbase";
const res = await cloudbase.deleteFile({
fileList: ["cloud://xxx.png"] // 文件 fileID 列表
});
if (res.fileList[0].code === "SUCCESS") {
console.log("删除成功");
}
完整示例:
<template>
<view>
<view>
<text>文件ID:</text>
<input v-model="fileId" placeholder="请输入文件ID (cloud://xxx.png)" />
</view>
<button :disabled="!fileId" @click="deleteFile">删除文件</button>
</view>
</template>
<script>
import cloudbase from "./utils/cloudbase";
export default {
data() {
return {
fileId: ""
};
},
methods: {
// 删除文件
async deleteFile() {
try {
const res = await cloudbase.deleteFile({
fileList: [this.fileId]
});
if (res.fileList[0].code === "SUCCESS") {
uni.showToast({
title: "删除成功",
icon: "success"
});
this.fileId = "";
} else {
uni.showToast({
title: "删除失败",
icon: "none"
});
}
} catch (error) {
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>
生图模型通过调用云函数来实现,在生图模型页面点击「一键创建云函数」,函数调用示例如下:
调用方式:
import { cloudbase } from "./utils/cloudbase";
// 调用生图云函数
const res = await cloudbase.callFunction({
name: "<YOUR_FUNCTION_NAME>",
data: {
prompt: "一只可爱的猫咪在阳光下玩耍"
}
});
const result = res.result;
if (result.success) {
// 生成成功
console.log("生成成功!");
console.log("图片URL:", result.imageUrl);
console.log("优化后的提示词:", result.revised_prompt);
// 使用图片
// 注意:图片URL有效期为24小时,请及时保存或转存
} else {
// 生成失败
console.error("生成失败:", result.code, result.message);
}
完整示例:
<template>
<view>
<view>
<text>图片描述:</text>
<input v-model="prompt" placeholder="请输入图片描述" />
</view>
<button :disabled="!prompt || loading" @click="generateImage">
{{ loading ? "生成中..." : "生成图片" }}
</button>
<view v-if="message">
<text>
{{ message }}
</text>
</view>
<view v-if="imageUrl">
<image></image>
<text>
注意:图片URL有效期为24小时,请及时保存
</text>
</view>
</view>
</template>
<script>
import cloudbase from "./utils/cloudbase";
export default {
data() {
return {
prompt: "",
imageUrl: "",
message: "",
loading: false
};
},
methods: {
// 生成图片
async generateImage() {
this.loading = true;
this.message = "";
this.imageUrl = "";
try {
uni.showLoading({
title: "生成中..."
});
// 调用生图云函数
const res = await cloudbase.callFunction({
name: "<YOUR_FUNCTION_NAME>",
data: {
prompt: this.prompt
}
});
const result = res.result;
if (result.success) {
this.imageUrl = result.imageUrl;
this.message = "生成成功!";
uni.hideLoading();
uni.showToast({
title: "生成成功",
icon: "success"
});
} else {
this.message = `生成失败:${result.message}`;
uni.hideLoading();
uni.showToast({
title: "生成失败",
icon: "none"
});
}
} catch (error) {
this.message = "调用失败:" + error.message;
uni.hideLoading();
uni.showToast({
title: "调用失败",
icon: "none"
});
} finally {
this.loading = false;
}
}
}
};
</script>