用 Vue 3 构建一个用户管理应用
探索适用于你 Supabase 应用的即插即用 UI 组件。
基于 shadcn/ui 构建的 UI 组件,通过一个命令连接到 Supabase。
🌐 UI components built on shadcn/ui that connect to Supabase via a single command.
探索组件本教程演示了如何构建一个基本的用户管理应用。该应用可以进行用户认证和识别,将用户的个人资料信息存储在数据库中,并允许用户登录、更新他们的个人资料信息以及上传头像。该应用使用了:
🌐 This tutorial demonstrates how to build a basic user management app. The app authenticates and identifies the user, stores their profile information in the database, and allows the user to log in, update their profile details, and upload a profile photo. The app uses:
- Supabase 数据库 - 一个用于存储用户数据的 Postgres 数据库,并且有 行级安全,所以数据是受保护的,用户只能访问自己的信息。
- Supabase Auth - 允许用户注册和登录。
- Supabase 存储 - 允许用户上传个人头像。

如果你在跟着这个指南操作时遇到困难,你可以在GitHub上找到完整示例。
🌐 If you get stuck while working through this guide, you can find the full example on GitHub.
项目设置 #
🌐 Project setup
在你开始构建之前,你需要先设置数据库和 API。你可以通过在 Supabase 中启动一个新项目,然后在数据库中创建一个“架构”来完成这一步。
🌐 Before you start building you need to set up the Database and API. You can do this by starting a new Project in Supabase and then creating a "schema" inside the database.
创建一个项目 #
🌐 Create a project
- 在 Supabase 仪表板中创建一个新项目。
- 输入你的项目详情。
- 等新数据库上线。
设置数据库模式 #
🌐 Set up the database schema
现在设置数据库模式。你可以在 SQL 编辑器中使用“用户管理入门”快速开始,也可以复制粘贴下面的 SQL 并运行。
🌐 Now set up the database schema. You can use the "User Management Starter" quickstart in the SQL Editor, or you can copy/paste the SQL from below and run it.
- 在仪表板中转到SQL 编辑器页面。
- 点击 社区 > 快速入门 标签下的 用户管理入门。
- 点击运行。
你可以通过运行 db pull 命令将数据库架构拉到本地项目。查看本地开发文档获取详细说明。
🌐 You can pull the database schema down to your local project by running the db pull command. Read the local development docs for detailed instructions.
1supabase link --project-ref <project-id>2# You can get <project-id> from your project's dashboard URL: https://supabase.com/dashboard/project/<project-id>3supabase db pull获取 API 详情 #
🌐 Get API details
要与数据库表中的数据进行交互,你可以使用封装了自动生成的数据 API 端点的客户端库,并使用来自项目 Connect 对话框的项目 URL 和密钥进行认证。
🌐 To interact with data in database tables, you use the client libraries that wrap the auto-generated Data API endpoints, authenticating using the Project URL and key from the project Connect dialog.
阅读 API 密钥文档 以全面了解所有密钥类型、用途以及在哪里可以找到它们。
正在构建应用 #
🌐 Building the app
从零开始搭建 Vue 3 应用。
🌐 Start building the Vue 3 app from scratch.
初始化一个 Vue 3 应用 #
🌐 Initialize a Vue 3 app
本指南使用 Vite with Vue 3 模板 来初始化一个名为 supabase-vue-3 的应用:
🌐 This guide uses Vite with Vue 3 Template to initialize
an app called supabase-vue-3:
1# npm 6.x2npm create vite@latest supabase-vue-3 --template vue34# npm 7+, extra double-dash is needed:5npm create vite@latest supabase-vue-3 -- --template vue67cd supabase-vue-3然后安装唯一的额外依赖:supabase-js
🌐 Then install the only additional dependency: supabase-js
1npm install @supabase/supabase-js最后,将环境变量保存在 .env 文件中,你需要之前复制的 API URL 和密钥 earlier。
🌐 And finally save the environment variables in a .env file, you need the API URL and the key that you copied earlier.
1VITE_SUPABASE_URL=YOUR_SUPABASE_URL2VITE_SUPABASE_PUBLISHABLE_KEY=YOUR_SUPABASE_PUBLISHABLE_KEY在设置好 API 凭证后,创建一个 src/supabase.js 辅助文件来初始化 Supabase 客户端。这些变量会在浏览器中公开,不过没关系,因为你已经在数据库上启用了 行级安全。
🌐 With the API credentials in place, create an src/supabase.js helper file to initialize the Supabase client. These variables are exposed
on the browser, and that's fine since you have Row Level Security enabled on the Database.
1import { createClient } from '@supabase/supabase-js'23const supabaseUrl = import.meta.env.VITE_SUPABASE_URL4const supabasePublishableKey = import.meta.env.VITE_SUPABASE_PUBLISHABLE_KEY56export const supabase = createClient(supabaseUrl, supabasePublishableKey)应用风格(可选) #
🌐 App styling (optional)
一个可选步骤是更新 CSS 文件 src/style.css 来让应用看起来更好。你可以在示例仓库中找到这个文件的完整内容。
🌐 An optional step is to update the CSS file src/style.css to make the app look better.
You can find the full contents of this file in the example repository.
设置一个登录组件 #
🌐 Set up a login component
设置一个 src/components/Auth.vue 组件来管理添加魔法链接作为选项,这样用户就可以通过电子邮件登录,而无需使用密码。
🌐 Set up an src/components/Auth.vue component to manage to add Magic Links as an option, so users can sign in with their email without using passwords.
1<script setup>2import { ref } from 'vue'3import { supabase } from '../supabase'45const loading = ref(false)6const email = ref('')78const handleLogin = async () => {9 try {10 loading.value = true11 const { error } = await supabase.auth.signInWithOtp({ email: email.value })12 if (error) throw error13 alert('Check your email for the login link!')14 } catch (error) {15 if (error instanceof Error) {16 alert(error.message)17 }18 } finally {19 loading.value = false20 }21}22</script>2324<template>25 <form class="row flex-center flex" @submit.prevent="handleLogin">26 <div class="col-6 form-widget">27 <h1 class="header">Supabase + Vue 3</h1>28 <p class="description">Sign in via magic link with your email below</p>29 <div>30 <input class="inputField" type="email" placeholder="Your email" v-model="email" />31 </div>32 <div>33 <input type="submit" class="button block" :value="loading ? 'Loading' : 'Send magic link'"34 :disabled="loading" />35 </div>36 </div>37 </form>38</template>账户页面 #
🌐 Account page
用户登录后,允许他们编辑个人资料详情并管理账户。
创建一个新的 src/components/Account.vue 组件来处理这个功能。
🌐 After a user signs in, allow them to edit their profile details and manage their account.
Create a new src/components/Account.vue component to handle this.
1<script setup>2import { supabase } from '../supabase'3import { onMounted, ref, toRefs } from 'vue'45// ...678const props = defineProps(['claims'])9const { claims } = toRefs(props)1011const loading = ref(true)12const username = ref('')13const website = ref('')14const avatar_url = ref('')1516onMounted(() => {17 getProfile()18})1920async function getProfile() {21 try {22 loading.value = true23 let { data, error, status } = await supabase24 .from('profiles')25 .select(`username, website, avatar_url`)26 .eq('id', claims.value.sub)27 .single()2829 if (error && status !== 406) throw error3031 if (data) {32 username.value = data.username33 website.value = data.website34 avatar_url.value = data.avatar_url35 }36 } catch (error) {37 alert(error.message)38 } finally {39 loading.value = false40 }41}4243async function updateProfile() {44 try {45 loading.value = true46 const updates = {47 id: claims.value.sub,48 username: username.value,49 website: website.value,50 avatar_url: avatar_url.value,51 updated_at: new Date(),52 }5354 let { error } = await supabase.from('profiles').upsert(updates)5556 if (error) throw error57 } catch (error) {58 alert(error.message)59 } finally {60 loading.value = false61 }62}6364async function signOut() {65 try {66 loading.value = true67 let { error } = await supabase.auth.signOut()68 if (error) throw error69 } catch (error) {70 alert(error.message)71 } finally {72 loading.value = false73 }74}75</script>7677<template>78 <form class="form-widget" @submit.prevent="updateProfile">7980 // ...8182 <div>83 <label for="email">Email</label>84 <input id="email" type="text" :value="claims.email" disabled />85 </div>86 <div>87 <label for="username">Name</label>88 <input id="username" type="text" v-model="username" />89 </div>90 <div>91 <label for="website">Website</label>92 <input id="website" type="url" v-model="website" />93 </div>9495 <div>96 <input type="submit" class="button primary block" :value="loading ? 'Loading ...' : 'Update'"97 :disabled="loading" />98 </div>99100 <div>101 <button class="button block" @click="signOut" :disabled="loading">102 Sign Out103 </button>104 </div>105 </form>106</template>头像照片 #
🌐 Profile photos
接下来,添加一个让用户上传个人资料照片的方式。Supabase 会为每个项目配置 Storage,用于管理像照片和视频这样的大文件。
🌐 Next, add a way for users to upload a profile photo. Supabase configures every project with Storage for managing large files like photos and videos.
创建一个上传小工具 #
🌐 Create an upload widget
创建一个新的 src/components/Avatar.vue 组件,让用户可以上传个人照片:
🌐 Create a new src/components/Avatar.vue component that allows users to upload profile photos:
1<script setup>2import { ref, toRefs, watch } from 'vue'3import { supabase } from '../supabase'45const prop = defineProps(['path', 'size'])6const { path, size } = toRefs(prop)78const emit = defineEmits(['upload', 'update:path'])9const uploading = ref(false)10const src = ref('')11const files = ref()1213const downloadImage = async () => {14 try {15 const { data, error } = await supabase.storage16 .from('avatars')17 .download(path.value)18 if (error) throw error19 src.value = URL.createObjectURL(data)20 } catch (error) {21 console.error('Error downloading image: ', error.message)22 }23}2425const uploadAvatar = async (evt) => {26 files.value = evt.target.files27 try {28 uploading.value = true29 if (!files.value || files.value.length === 0) {30 throw new Error('You must select an image to upload.')31 }3233 const file = files.value[0]34 const fileExt = file.name.split('.').pop()35 const filePath = `${Math.random()}.${fileExt}`3637 let { error: uploadError } = await supabase.storage38 .from('avatars')39 .upload(filePath, file)4041 if (uploadError) throw uploadError42 emit('update:path', filePath)43 emit('upload')44 } catch (error) {45 alert(error.message)46 } finally {47 uploading.value = false48 }49}5051watch(path, () => {52 if (path.value) downloadImage()53})54</script>5556<template>57 <div>58 <img v-if="src" :src="src" alt="Avatar" class="avatar image"59 :style="{ height: size + 'em', width: size + 'em' }" />60 <div v-else class="avatar no-image" :style="{ height: size + 'em', width: size + 'em' }" />6162 <div :style="{ width: size + 'em' }">63 <label class="button primary block" for="single">64 {{ uploading ? "Uploading ..." : "Upload" }}65 </label>66 <input style="visibility: hidden; position: absolute" type="file" id="single" accept="image/*"67 @change="uploadAvatar" :disabled="uploading" />68 </div>69 </div>70</template>更新账户组件 #
🌐 Update the Account component
创建了 Avatar 组件后,更新 src/components/Account.vue 来包含它:
🌐 With the Avatar component created, update src/components/Account.vue to include it:
1<script setup>2import { supabase } from '../supabase'3import { onMounted, ref, toRefs } from 'vue'4import Avatar from './Avatar.vue';56const props = defineProps(['claims'])7const { claims } = toRefs(props)89const loading = ref(true)10const username = ref('')11const website = ref('')12const avatar_url = ref('')1314onMounted(() => {15 getProfile()16})1718async function getProfile() {19 try {20 loading.value = true21 let { data, error, status } = await supabase22 .from('profiles')23 .select(`username, website, avatar_url`)24 .eq('id', claims.value.sub)25 .single()2627 if (error && status !== 406) throw error2829 if (data) {30 username.value = data.username31 website.value = data.website32 avatar_url.value = data.avatar_url33 }34 } catch (error) {35 alert(error.message)36 } finally {37 loading.value = false38 }39}4041async function updateProfile() {42 try {43 loading.value = true44 const updates = {45 id: claims.value.sub,46 username: username.value,47 website: website.value,48 avatar_url: avatar_url.value,49 updated_at: new Date(),50 }5152 let { error } = await supabase.from('profiles').upsert(updates)5354 if (error) throw error55 } catch (error) {56 alert(error.message)57 } finally {58 loading.value = false59 }60}6162async function signOut() {63 try {64 loading.value = true65 let { error } = await supabase.auth.signOut()66 if (error) throw error67 } catch (error) {68 alert(error.message)69 } finally {70 loading.value = false71 }72}73</script>7475<template>76 <form class="form-widget" @submit.prevent="updateProfile">77 <Avatar v-model:path="avatar_url" @upload="updateProfile" size="10" />78 <div>79 <label for="email">Email</label>80 <input id="email" type="text" :value="claims.email" disabled />81 </div>82 <div>83 <label for="username">Name</label>84 <input id="username" type="text" v-model="username" />85 </div>86 <div>87 <label for="website">Website</label>88 <input id="website" type="url" v-model="website" />89 </div>9091 <div>92 <input type="submit" class="button primary block" :value="loading ? 'Loading ...' : 'Update'"93 :disabled="loading" />94 </div>9596 <div>97 <button class="button block" @click="signOut" :disabled="loading">98 Sign Out99 </button>100 </div>101 </form>102</template>触发! #
🌐 Launch!
在所有组件就位后,更新 App.vue:
🌐 With all the components in place, update App.vue:
1<script setup>2import { onMounted, ref } from 'vue'3import Account from './components/Account.vue'4import Auth from './components/Auth.vue'5import { supabase } from './supabase'67const claims = ref()89onMounted(() => {10 supabase.auth.getClaims().then(({ data }) => {11 claims.value = data.claims12 })1314 supabase.auth.onAuthStateChange(async () => {15 const { data } = await supabase.auth.getClaims()16 claims.value = data.claims17 })18})19</script>2021<template>22 <div class="container" style="padding: 50px 0 100px 0">23 <Account v-if="claims" :claims="claims" />24 <Auth v-else />25 </div>26</template>完成后,在终端窗口运行这个:
🌐 Once that's done, run this in a terminal window:
1npm run dev然后打开浏览器访问 localhost:5173,你应该能看到完成的应用。
🌐 And then open the browser to localhost:5173 and you should see the completed app.

在这个阶段,你已经有了一个完全可用的应用!
🌐 At this stage you have a fully functional application!