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.

Project URL
Publishable key

正在构建应用 #

🌐 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.x
2
npm create vite@latest supabase-vue-3 --template vue
3
4
# npm 7+, extra double-dash is needed:
5
npm create vite@latest supabase-vue-3 -- --template vue
6
7
cd supabase-vue-3

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

🌐 Then install the only additional dependency: supabase-js

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

1
VITE_SUPABASE_URL=YOUR_SUPABASE_URL
2
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
1
import { createClient } from '@supabase/supabase-js'
2
3
const supabaseUrl = import.meta.env.VITE_SUPABASE_URL
4
const supabasePublishableKey = import.meta.env.VITE_SUPABASE_PUBLISHABLE_KEY
5
6
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 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.

src/components/Auth.vue
1
<script setup>
2
import { ref } from 'vue'
3
import { supabase } from '../supabase'
4
5
const loading = ref(false)
6
const email = ref('')
7
8
const handleLogin = async () => {
9
try {
10
loading.value = true
11
const { error } = await supabase.auth.signInWithOtp({ email: email.value })
12
if (error) throw error
13
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 = false
20
}
21
}
22
</script>
23
24
<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>
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
1
<script setup>
2
import { supabase } from '../supabase'
3
import { onMounted, ref, toRefs } from 'vue'
4
5
// ...
6
7
8
const props = defineProps(['claims'])
9
const { claims } = toRefs(props)
10
11
const loading = ref(true)
12
const username = ref('')
13
const website = ref('')
14
const avatar_url = ref('')
15
16
onMounted(() => {
17
getProfile()
18
})
19
20
async function getProfile() {
21
try {
22
loading.value = true
23
let { data, error, status } = await supabase
24
.from('profiles')
25
.select(`username, website, avatar_url`)
26
.eq('id', claims.value.sub)
27
.single()
28
29
if (error && status !== 406) throw error
30
31
if (data) {
32
username.value = data.username
33
website.value = data.website
34
avatar_url.value = data.avatar_url
35
}
36
} catch (error) {
37
alert(error.message)
38
} finally {
39
loading.value = false
40
}
41
}
42
43
async function updateProfile() {
44
try {
45
loading.value = true
46
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
}
53
54
let { error } = await supabase.from('profiles').upsert(updates)
55
56
if (error) throw error
57
} catch (error) {
58
alert(error.message)
59
} finally {
60
loading.value = false
61
}
62
}
63
64
async function signOut() {
65
try {
66
loading.value = true
67
let { error } = await supabase.auth.signOut()
68
if (error) throw error
69
} catch (error) {
70
alert(error.message)
71
} finally {
72
loading.value = false
73
}
74
}
75
</script>
76
77
<template>
78
<form class="form-widget" @submit.prevent="updateProfile">
79
80
// ...
81
82
<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>
94
95
<div>
96
<input type="submit" class="button primary block" :value="loading ? 'Loading ...' : 'Update'"
97
:disabled="loading" />
98
</div>
99
100
<div>
101
<button class="button block" @click="signOut" :disabled="loading">
102
Sign Out
103
</button>
104
</div>
105
</form>
106
</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
1
<script setup>
2
import { ref, toRefs, watch } from 'vue'
3
import { supabase } from '../supabase'
4
5
const prop = defineProps(['path', 'size'])
6
const { path, size } = toRefs(prop)
7
8
const emit = defineEmits(['upload', 'update:path'])
9
const uploading = ref(false)
10
const src = ref('')
11
const files = ref()
12
13
const downloadImage = async () => {
14
try {
15
const { data, error } = await supabase.storage
16
.from('avatars')
17
.download(path.value)
18
if (error) throw error
19
src.value = URL.createObjectURL(data)
20
} catch (error) {
21
console.error('Error downloading image: ', error.message)
22
}
23
}
24
25
const uploadAvatar = async (evt) => {
26
files.value = evt.target.files
27
try {
28
uploading.value = true
29
if (!files.value || files.value.length === 0) {
30
throw new Error('You must select an image to upload.')
31
}
32
33
const file = files.value[0]
34
const fileExt = file.name.split('.').pop()
35
const filePath = `${Math.random()}.${fileExt}`
36
37
let { error: uploadError } = await supabase.storage
38
.from('avatars')
39
.upload(filePath, file)
40
41
if (uploadError) throw uploadError
42
emit('update:path', filePath)
43
emit('upload')
44
} catch (error) {
45
alert(error.message)
46
} finally {
47
uploading.value = false
48
}
49
}
50
51
watch(path, () => {
52
if (path.value) downloadImage()
53
})
54
</script>
55
56
<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' }" />
61
62
<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>
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
1
<script setup>
2
import { supabase } from '../supabase'
3
import { onMounted, ref, toRefs } from 'vue'
4
import Avatar from './Avatar.vue';
5
6
const props = defineProps(['claims'])
7
const { claims } = toRefs(props)
8
9
const loading = ref(true)
10
const username = ref('')
11
const website = ref('')
12
const avatar_url = ref('')
13
14
onMounted(() => {
15
getProfile()
16
})
17
18
async function getProfile() {
19
try {
20
loading.value = true
21
let { data, error, status } = await supabase
22
.from('profiles')
23
.select(`username, website, avatar_url`)
24
.eq('id', claims.value.sub)
25
.single()
26
27
if (error && status !== 406) throw error
28
29
if (data) {
30
username.value = data.username
31
website.value = data.website
32
avatar_url.value = data.avatar_url
33
}
34
} catch (error) {
35
alert(error.message)
36
} finally {
37
loading.value = false
38
}
39
}
40
41
async function updateProfile() {
42
try {
43
loading.value = true
44
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
}
51
52
let { error } = await supabase.from('profiles').upsert(updates)
53
54
if (error) throw error
55
} catch (error) {
56
alert(error.message)
57
} finally {
58
loading.value = false
59
}
60
}
61
62
async function signOut() {
63
try {
64
loading.value = true
65
let { error } = await supabase.auth.signOut()
66
if (error) throw error
67
} catch (error) {
68
alert(error.message)
69
} finally {
70
loading.value = false
71
}
72
}
73
</script>
74
75
<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>
90
91
<div>
92
<input type="submit" class="button primary block" :value="loading ? 'Loading ...' : 'Update'"
93
:disabled="loading" />
94
</div>
95
96
<div>
97
<button class="button block" @click="signOut" :disabled="loading">
98
Sign Out
99
</button>
100
</div>
101
</form>
102
</template>
View source

触发! #

🌐 Launch!

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

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

src/App.vue
1
<script setup>
2
import { onMounted, ref } from 'vue'
3
import Account from './components/Account.vue'
4
import Auth from './components/Auth.vue'
5
import { supabase } from './supabase'
6
7
const claims = ref()
8
9
onMounted(() => {
10
supabase.auth.getClaims().then(({ data }) => {
11
claims.value = data.claims
12
})
13
14
supabase.auth.onAuthStateChange(async () => {
15
const { data } = await supabase.auth.getClaims()
16
claims.value = data.claims
17
})
18
})
19
</script>
20
21
<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>
View source

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

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

1
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!