Vue(Vite) 快速开始
- 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:在 Vue(Vite) 应用中集成 CloudBase Web SDK,包括认证和数据库功能准备工作
在开始之前,请确保您已完成以下准备:
- 开通云开发环境:开通云开发环境
- 安装 Node.js:下载 Node.js(建议 LTS 版本)
更多详情请参考:Vue(Vite) 完整文档
安装 SDK
@cloudbase/js-sdk 可以让您在 Web 端(如 PC Web 页面、微信公众平台 H5 等)使用 JavaScript 访问 CloudBase 服务和资源。
npm
npm i @cloudbase/js-sdk
yarn
yarn add @cloudbase/js-sdk
pnpm
pnpm add @cloudbase/js-sdk
初始化 SDK
新增如下代码到您的 Vue 项目
src/utils/cloudbase.js
import cloudbaseSDK from "@cloudbase/js-sdk";
export const cloudbase = cloudbaseSDK.init({
env: import.meta.env.VITE_CLOUDBASE_ENV_ID,
region: import.meta.env.VITE_CLOUDBASE_REGION,
accessKey: import.meta.env.VITE_CLOUDBASE_ACCESS_KEY
});
.env
# 环境ID
VITE_CLOUDBASE_ENV_ID={%ENV_ID%}
# 环境所在地域
VITE_CLOUDBASE_REGION={%REGION%}
# 匿名访问令牌
VITE_CLOUDBASE_ACCESS_KEY={%PUBLISHABLE_KEY%}
身份认证
- 短信验证码注册
- 邮箱验证码注册
- 账号密码登录
- 短信验证码登录
- 邮箱验证码登录
- Google 授权登录
使用 短信验证码注册 请先前往 身份认证/登录方式 开启 短信验证码
调用方式:
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>
<div>
<label>手机号:</label>
<input v-model="phone" placeholder="13800000000" />
<div>
<label>验证码:</label>
<input v-model="code" placeholder="验证码" />
<button :disabled="!phone" @click="sendCode">发送验证码</button>
</div>
<button :disabled="!verificationId || !code" @click="register">注册</button>
<p>{{ message }}</p>
</div>
</template>
<script setup>
import { ref } from "vue";
import { cloudbase } from "./utils/cloudbase";
const phone = ref("");
const code = ref("");
const verificationId = ref("");
const message = ref("");
// 发送验证码
const sendCode = async () => {
try {
const auth = cloudbase.auth();
const res = await auth.getVerification({ phone_number: phone.value });
verificationId.value = res.verification_id;
message.value = "验证码已发送!";
} catch (error) {
message.value = "发送失败:" + error.message;
}
};
// 注册
const register = async () => {
try {
const auth = cloudbase.auth();
// 验证验证码
const verifyRes = await auth.verify({
verification_id: verificationId.value,
verification_code: code.value,
});
// 注册(如用户已存在则自动登录)
await auth.signUp({
phone_number: `+86 ${phone.value}`,
verification_code: code.value,
verification_token: verifyRes.verification_token,
name: `user_${phone.value.slice(-4)}`,
password: "admin@123"
});
message.value = "注册成功!";
} catch (error) {
message.value = "注册失败:" + 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>
<div>
<label>邮箱:</label>
<input v-model="email" placeholder="example@email.com" />
<div>
<label>验证码:</label>
<input v-model="code" placeholder="验证码" />
<button :disabled="!email" @click="sendCode">发送验证码</button>
</div>
<button :disabled="!verificationId || !code" @click="register">注册</button>
<p>{{ message }}</p>
</div>
</template>
<script setup>
import { ref } from "vue";
import { cloudbase } from "./utils/cloudbase";
const email = ref("");
const code = ref("");
const verificationId = ref("");
const message = ref("");
// 发送验证码
const sendCode = async () => {
try {
const auth = cloudbase.auth();
const res = await auth.getVerification({ email: email.value });
verificationId.value = res.verification_id;
message.value = "验证码已发送!";
} catch (error) {
message.value = "发送失败:" + error.message;
}
};
// 注册
const register = async () => {
try {
const auth = cloudbase.auth();
// 验证验证码
const verifyRes = await auth.verify({
verification_id: verificationId.value,
verification_code: code.value,
});
// 注册(如用户已存在则自动登录)
await auth.signUp({
email: email.value,
verification_code: code.value,
verification_token: verifyRes.verification_token,
name: `user_${email.value.slice(-4)}`,
password: "admin@123"
});
message.value = "注册成功!";
} catch (error) {
message.value = "注册失败:" + error.message;
}
};
</script>
使用 账号密码登录 请先前往 身份认证/登录方式 开启 用户名密码登录
调用方式:
import { cloudbase } from "./utils/cloudbase";
const auth = cloudbase.auth();
await auth.signIn({
username, // 可以是用户名、手机号或邮箱
password
});
完整示例:
<template>
<div>
<label>账号:</label>
<input v-model="username" placeholder="用户名/手机号/邮箱" />
注:手机号登录请添加区号 +86
<br />
<label>密码:</label>
<input
type="password"
v-model="password"
placeholder="请输入密码"
/>
<br />
<button :disabled="!username || !password" @click="login">登录</button>
<p>{{ message }}</p>
</div>
</template>
<script setup>
import { ref } from "vue";
import { cloudbase } from "./utils/cloudbase";
const username = ref("");
const password = ref("");
const message = ref("");
// 登录
const login = async () => {
try {
const auth = cloudbase.auth();
await auth.signIn({
username: username.value, // 可以是用户名、手机号或邮箱
password: password.value,
});
message.value = "登录成功!";
} catch (error) {
message.value = "登录失败:" + 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>
<div>
<label>手机号:</label>
<input v-model="phone" placeholder="13800000000" />
<div>
<label>验证码:</label>
<input v-model="code" placeholder="验证码" />
<button @click="sendCode" :disabled="!phone">发送验 证码</button>
</div>
<button @click="login" :disabled="!verificationInfo || !code">登录</button>
<p>{{ message }}</p>
</div>
</template>
<script setup>
import { ref } from "vue";
import { cloudbase } from "./utils/cloudbase";
const phone = ref("");
const code = ref("");
const verificationInfo = ref(null);
const message = ref("");
// 发送验证码
const sendCode = async () => {
try {
const auth = cloudbase.auth();
const res = await auth.getVerification({ phone_number: `+86 ${phone.value}` });
verificationInfo.value = res;
message.value = "验证码已发送!";
} catch (error) {
message.value = "发送失败:" + error.message;
}
};
// 登录
const login = async () => {
try {
const auth = cloudbase.auth();
await auth.signInWithSms({
verificationInfo: verificationInfo.value,
verificationCode: code.value,
phoneNum: `+86 ${phone.value}`
});
message.value = "登录成功!";
} catch (error) {
message.value = "登录失败:" + 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>
<div>
<label>邮箱:</label>
<input v-model="email" placeholder="example@email.com" />
<div>
<label>验证码:</label>
<input v-model="code" placeholder="验证码" />
<button @click="sendCode" :disabled="!email">发送验证码</button>
</div>
<button @click="login" :disabled="!verificationInfo || !code">登录</button>
<p>{{ message }}</p>
</div>
</template>
<script setup>
import { ref } from "vue";
import { cloudbase } from "./utils/cloudbase";
const email = ref("");
const code = ref("");
const verificationInfo = ref(null);
const message = ref("");
// 发送验证码
const sendCode = async () => {
try {
const auth = cloudbase.auth();
const res = await auth.getVerification({ email: email.value });
verificationInfo.value = res;
message.value = "验证码已发送!";
} catch (error) {
message.value = "发送失败:" + error.message;
}
};
// 登录
const login = async () => {
try {
const auth = cloudbase.auth();
await auth.signInWithEmail({
verificationInfo: verificationInfo.value,
verificationCode: code.value,
email: email.value
});
message.value = "登录成功!";
} catch (error) {
message.value = "登录失败:" + error.message;
}
};
</script>
使用 Google 授权登录 请先前往 身份认证/登录方式 开启 Google 授权登录
调用方式:
import { cloudbase } from "./utils/cloudbase";
const auth = cloudbase.auth();
// 步骤1:生成Google授权URL并跳转
const state = Date.now().toString();
localStorage.setItem("google_login_state", state);
const { uri } = await auth.genProviderRedirectUri({
provider_id: "google",
provider_redirect_uri: window.location.href,
state: state
});
window.location.href = uri;
// 步骤2:使用code换取provider_token
const { provider_token } = await auth.grantProviderToken({
provider_id: "google",
provider_redirect_uri: window.location.origin + window.location.pathname,
provider_code: code
});
// 步骤3:使用provider_token登录
await auth.signInWithProvider({
provider_token: provider_token
});
完整示例:
<template>
<div>
<button v-if="!isCallback" @click="startGoogleLogin">Google登录</button>
<p v-if="isCallback">正在处理Google登录...</p>
<p>
{{ message }}
</p>
</div>
</template>
<script setup>
import { ref, onMounted } from "vue";
import { cloudbase } from "./utils/cloudbase";
const message = ref("");
const isCallback = ref(false);
onMounted(() => {
// 检查是否是Google回调页面
const urlParams = new URLSearchParams(window.location.search);
const code = urlParams.get("code");
const state = urlParams.get("state");
if (code && state) {
isCallback.value = true;
handleGoogleCallback(code, state);
}
});
// 步骤1:跳转到Google授权页
const startGoogleLogin = async () => {
try {
const auth = cloudbase.auth();
const state = Date.now().toString(); // 生成唯一标识,防止CSRF攻击
// 保存state到本地,用于回调时验证
localStorage.setItem("google_login_state", state);
// 生成Google授权URL
const { uri } = await auth.genProviderRedirectUri({
provider_id: "google", // 固定值,代表Google开放平台
provider_redirect_uri: window.location.href, // 授权后回调当前页面
state: state,
});
// 跳转到Google授权页
window.location.href = uri;
} catch (error) {
message.value = "跳转失败:" + error.message;
}
};
// 步骤2和3:处理Google回调并完成登录
const handleGoogleCallback = async (code, state) => {
try {
// 验证state是否匹配,防止CSRF攻击
const savedState = localStorage.getItem("google_login_state");
if (savedState !== state) {
message.value = "登录失败:状态验证失败";
return;
}
const auth = cloudbase.auth();
// 使用code换取provider_token
const { provider_token } = await auth.grantProviderToken({
provider_id: "google",
provider_redirect_uri: window.location.origin + window.location.pathname,
provider_code: code,
});
try {
// 尝试直接登录
await auth.signInWithProvider({
provider_token: provider_token,
});
message.value = "登录成功!";
// 清除URL参数并清除本地存储
localStorage.removeItem("google_login_state");
window.history.replaceState({}, document.title, window.location.pathname);
} catch (loginError) {
// 如果是首次Google登录,需要先注册并绑定
if (loginError.error === "not_found") {
message.value = "检测到首次Google登录,需要绑定账号...";
// 这里需要引导用户完成注册流程
// 例如:收集手机号验证码进行注册
// 注册成功后调用 bindWithProvider 绑定Google身份
// 示例:假设已有其他方式注册的账号,直接绑定
await auth.bindWithProvider({
provider_token: provider_token,
});
// 绑定成功后重新登录
await auth.signInWithProvider({
provider_token: provider_token,
});
message.value = "绑定并登录成功!";
// 清除URL参数和本地存储
localStorage.removeItem("google_login_state");
window.history.replaceState({}, document.title, window.location.pathname);
} else {
throw loginError;
}
}
} catch (error) {
message.value = "登录失败:" + error.message;
localStorage.removeItem("google_login_state");
}
};
</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>
<ul>
<li v-for="item in data" :key="item._id">{{ item.title }}</li>
</ul>
</template>
<script setup>
import { ref, onMounted } from "vue";
import { cloudbase } from "./utils/cloudbase";
const data = ref([]);
const getData = async () => {
// 查询 {%TABLE_NAME%} 表前10条数据
const db = cloudbase.database();
const res = await db.collection("{%TABLE_NAME%}").limit(10).get();
data.value = res.data || [];
};
onMounted(() => {
getData();
});
</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>
<div>
<button @click="addData">新增</button>
<p>{{ message }}</p>
</div>
</template>
<script setup>
import { ref } from "vue";
import { cloudbase } from "./utils/cloudbase";
const message = ref("");
const addData = async () => {
try {
// 新增 {%TABLE_NAME%} 表数据
const db = cloudbase.database();
const res = await db.collection("{%TABLE_NAME%}").add({ title: "示例标题" });
message.value = `新增成功! id: ${res.id}`;
} catch (error) {
message.value = "新增失败:" + error.message;
}
};
</script>
调用方式:
import { cloudbase } from "./utils/cloudbase";
// 更新 {%TABLE_NAME%} 表中 id 为指定值的数据
const db = cloudbase.database();
await db
.collection("{%TABLE_NAME%}")
.doc("<数据id>")
.update({ title: "新标题" });
完整示例:
<template>
<div>
<button @click="updateData">更新</button>
<p>{{ message }}</p>
</div>
</template>
<script setup>
import { ref } from "vue";
import { cloudbase } from "./utils/cloudbase";
const message = ref("");
const updateData = async () => {
try {
// 更新 {%TABLE_NAME%} 表中 id 为指定值的数据
const db = cloudbase.database();
await db.collection("{%TABLE_NAME%}").doc("<数据id>").update({ title: "新标题" });
message.value = "更新成功!";
} catch (error) {
message.value = "更新失败:" + error.message;
}
};
</script>
调用方式:
import { cloudbase } from "./utils/cloudbase";
// 删除 {%TABLE_NAME%} 表中 id 为指定值的数据
const db = cloudbase.database();
await db.collection("{%TABLE_NAME%}").doc("<数据id>").remove();
完整示例:
<template>
<div>
<button @click="deleteData">删除</button>
<p>{{ message }}</p>
</div>
</template>
<script setup>
import { ref } from "vue";
import { cloudbase } from "./utils/cloudbase";
const message = ref("");
const deleteData = async () => {
try {
// 删除 {%TABLE_NAME%} 表中 id 为指定值的数据
const db = cloudbase.database();
await db.collection("{%TABLE_NAME%}").doc("<数据id>").remove();
message.value = "删除成功!";
} catch (error) {
message.value = "删除失败:" + error.message;
}
};
</script>
云存储
- 上传文件