Skip to content
Getting Started

用 Vue 3 构建一个用户管理应用

本教程演示了如何构建一个基本的用户管理应用。该应用可以进行用户认证和识别,将用户的个人资料信息存储在数据库中,并允许用户登录、更新他们的个人资料信息以及上传头像。该应用使用了:

🌐 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 User Management example

项目设置 #

🌐 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

  1. 在 Supabase 仪表板中创建一个新项目。
  2. 输入你的项目详情。
  3. 等新数据库上线。

设置数据库模式 #

🌐 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.

  1. 在仪表板中转到SQL 编辑器页面。
  2. 在 参考 > 示例 选项卡下点击 用户管理入门。
  3. 点击运行。

获取 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.

正在构建应用 #

🌐 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:

# npm 6.x
npm create vite@latest supabase-vue-3 --template vue
# npm 7+, extra double-dash is needed:
npm create vite@latest supabase-vue-3 -- --template vue
cd supabase-vue-3

然后安装唯一的额外依赖:supabase-js

🌐 Then install the only additional dependency: supabase-js

npm 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.

VITE_SUPABASE_URL=YOUR_SUPABASE_URL
VITE_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.

src/supabase.js
import { createClient } from '@supabase/supabase-js'
const supabaseUrl = import.meta.env.VITE_SUPABASE_URL
const supabasePublishableKey = import.meta.env.VITE_SUPABASE_PUBLISHABLE_KEY
export const supabase = createClient(supabaseUrl, supabasePublishableKey)
View source

应用风格(可选) #

🌐 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 sign-in 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.

src/components/Auth.vue
<script setup>
import { ref } from 'vue'
import { supabase } from '../supabase'
const loading = ref(false)
const email = ref('')
const handleLogin = async () => {
try {
loading.value = true
const { error } = await supabase.auth.signInWithOtp({ email: email.value })
if (error) throw error
alert('Check your email for the login link!')
} catch (error) {
if (error instanceof Error) {
alert(error.message)
}
} finally {
loading.value = false
}
}
</script>
<template>
<form class="row flex-center flex" @submit.prevent="handleLogin">
<div class="col-6 form-widget">
<h1 class="header">Supabase + Vue 3</h1>
<p class="description">Sign in via magic link with your email below</p>
<div>
<input class="inputField" type="email" placeholder="Your email" v-model="email" />
</div>
<div>
<input type="submit" class="button block" :value="loading ? 'Loading' : 'Send magic link'"
:disabled="loading" />
</div>
</div>
</form>
</template>
View source

账户页面 #

🌐 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.

src/components/Account.vue
<script setup>
import { supabase } from '../supabase'
import { onMounted, ref, toRefs } from 'vue'
// ...
const props = defineProps(['claims'])
const { claims } = toRefs(props)
const loading = ref(true)
const username = ref('')
const website = ref('')
const avatar_url = ref('')
onMounted(() => {
getProfile()
})
async function getProfile() {
try {
loading.value = true
let { data, error, status } = await supabase
.from('profiles')
.select(`username, website, avatar_url`)
.eq('id', claims.value.sub)
.single()
if (error && status !== 406) throw error
if (data) {
username.value = data.username
website.value = data.website
avatar_url.value = data.avatar_url
}
} catch (error) {
alert(error.message)
} finally {
loading.value = false
}
}
async function updateProfile() {
try {
loading.value = true
const updates = {
id: claims.value.sub,
username: username.value,
website: website.value,
avatar_url: avatar_url.value,
updated_at: new Date(),
}
let { error } = await supabase.from('profiles').upsert(updates)
if (error) throw error
} catch (error) {
alert(error.message)
} finally {
loading.value = false
}
}
async function signOut() {
try {
loading.value = true
let { error } = await supabase.auth.signOut()
if (error) throw error
} catch (error) {
alert(error.message)
} finally {
loading.value = false
}
}
</script>
<template>
<form class="form-widget" @submit.prevent="updateProfile">
// ...
<div>
<label for="email">Email</label>
<input id="email" type="text" :value="claims.email" disabled />
</div>
<div>
<label for="username">Name</label>
<input id="username" type="text" v-model="username" />
</div>
<div>
<label for="website">Website</label>
<input id="website" type="url" v-model="website" />
</div>
<div>
<input type="submit" class="button primary block" :value="loading ? 'Loading ...' : 'Update'"
:disabled="loading" />
</div>
<div>
<button class="button block" @click="signOut" :disabled="loading">
Sign Out
</button>
</div>
</form>
</template>
View source

头像照片 #

🌐 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:

src/components/Avatar.vue
<script setup>
import { ref, toRefs, watch } from 'vue'
import { supabase } from '../supabase'
const prop = defineProps(['path', 'size'])
const { path, size } = toRefs(prop)
const emit = defineEmits(['upload', 'update:path'])
const uploading = ref(false)
const src = ref('')
const files = ref()
const downloadImage = async () => {
try {
const { data, error } = await supabase.storage
.from('avatars')
.download(path.value)
if (error) throw error
src.value = URL.createObjectURL(data)
} catch (error) {
console.error('Error downloading image: ', error.message)
}
}
const uploadAvatar = async (evt) => {
files.value = evt.target.files
try {
uploading.value = true
if (!files.value || files.value.length === 0) {
throw new Error('You must select an image to upload.')
}
const file = files.value[0]
const fileExt = file.name.split('.').pop()
const filePath = `${Math.random()}.${fileExt}`
let { error: uploadError } = await supabase.storage
.from('avatars')
.upload(filePath, file)
if (uploadError) throw uploadError
emit('update:path', filePath)
emit('upload')
} catch (error) {
alert(error.message)
} finally {
uploading.value = false
}
}
watch(path, () => {
if (path.value) downloadImage()
})
</script>
<template>
<div>
<img v-if="src" :src="src" alt="Avatar" class="avatar image"
:style="{ height: size + 'em', width: size + 'em' }" />
<div v-else class="avatar no-image" :style="{ height: size + 'em', width: size + 'em' }" />
<div :style="{ width: size + 'em' }">
<label class="button primary block" for="single">
{{ uploading ? "Uploading ..." : "Upload" }}
</label>
<input style="visibility: hidden; position: absolute" type="file" id="single" accept="image/*"
@change="uploadAvatar" :disabled="uploading" />
</div>
</div>
</template>
View source

更新账户组件 #

🌐 Update the Account component

创建了 Avatar 组件后,更新 src/components/Account.vue 来包含它:

🌐 With the Avatar component created, update src/components/Account.vue to include it:

src/components/Account.vue
<script setup>
import { supabase } from '../supabase'
import { onMounted, ref, toRefs } from 'vue'
import Avatar from './Avatar.vue';
const props = defineProps(['claims'])
const { claims } = toRefs(props)
const loading = ref(true)
const username = ref('')
const website = ref('')
const avatar_url = ref('')
onMounted(() => {
getProfile()
})
async function getProfile() {
try {
loading.value = true
let { data, error, status } = await supabase
.from('profiles')
.select(`username, website, avatar_url`)
.eq('id', claims.value.sub)
.single()
if (error && status !== 406) throw error
if (data) {
username.value = data.username
website.value = data.website
avatar_url.value = data.avatar_url
}
} catch (error) {
alert(error.message)
} finally {
loading.value = false
}
}
async function updateProfile() {
try {
loading.value = true
const updates = {
id: claims.value.sub,
username: username.value,
website: website.value,
avatar_url: avatar_url.value,
updated_at: new Date(),
}
let { error } = await supabase.from('profiles').upsert(updates)
if (error) throw error
} catch (error) {
alert(error.message)
} finally {
loading.value = false
}
}
async function signOut() {
try {
loading.value = true
let { error } = await supabase.auth.signOut()
if (error) throw error
} catch (error) {
alert(error.message)
} finally {
loading.value = false
}
}
</script>
<template>
<form class="form-widget" @submit.prevent="updateProfile">
<Avatar v-model:path="avatar_url" @upload="updateProfile" size="10" />
<div>
<label for="email">Email</label>
<input id="email" type="text" :value="claims.email" disabled />
</div>
<div>
<label for="username">Name</label>
<input id="username" type="text" v-model="username" />
</div>
<div>
<label for="website">Website</label>
<input id="website" type="url" v-model="website" />
</div>
<div>
<input type="submit" class="button primary block" :value="loading ? 'Loading ...' : 'Update'"
:disabled="loading" />
</div>
<div>
<button class="button block" @click="signOut" :disabled="loading">
Sign Out
</button>
</div>
</form>
</template>
View source

触发! #

🌐 Launch!

在所有组件就位后,更新 App.vue:

🌐 With all the components in place, update App.vue:

src/App.vue
<script setup>
import { onMounted, ref } from 'vue'
import Account from './components/Account.vue'
import Auth from './components/Auth.vue'
import { supabase } from './supabase'
const claims = ref()
onMounted(() => {
supabase.auth.getClaims().then(({ data }) => {
claims.value = data.claims
})
supabase.auth.onAuthStateChange(async () => {
const { data } = await supabase.auth.getClaims()
claims.value = data.claims
})
})
</script>
<template>
<div class="container" style="padding: 50px 0 100px 0">
<Account v-if="claims" :claims="claims" />
<Auth v-else />
</div>
</template>
View source

完成后,在终端窗口运行这个:

🌐 Once that's done, run this in a terminal window:

npm run dev

然后打开浏览器访问 localhost:5173,你应该能看到完成的应用。

🌐 And then open the browser to localhost:5173 and you should see the completed app.

Supabase Vue 3

在这个阶段,你已经有了一个完全可用的应用!

🌐 At this stage you have a fully functional application!