UsernameSettingPage.vue
2.79 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
<!--
* @Date: 2025-03-24 13:04:21
* @LastEditors: hookehuyr hookehuyr@gmail.com
* @LastEditTime: 2025-03-26 13:42:45
* @FilePath: /mlaj/src/views/profile/settings/UsernameSettingPage.vue
* @Description: 修改用户名页面
-->
<template>
<AppLayout title="">
<div class="bg-gradient-to-br from-green-50 via-green-100/30 to-blue-50/30 min-h-screen">
<div class="px-4 py-6">
<FrostedGlass class="rounded-xl overflow-hidden">
<div class="p-4">
<div class="space-y-4">
<div class="mb-6">
<label for="username" class="block text-sm font-medium text-gray-700 mb-2">新用户名</label>
<input
v-model="username"
type="text"
id="username"
placeholder="请输入新的用户名"
class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-green-500 focus:border-transparent"
/>
</div>
<van-button
@click="handleUsernameChange"
type="primary"
block
round
>
保存修改
</van-button>
</div>
</div>
</FrostedGlass>
</div>
</div>
</AppLayout>
</template>
<script setup>
import { ref, onMounted } from 'vue';
import AppLayout from '@/components/layout/AppLayout.vue';
import FrostedGlass from '@/components/ui/FrostedGlass.vue';
import { getUserInfoAPI, updateUserInfoAPI } from '@/api/users';
import { showToast } from 'vant';
import { useTitle } from '@vueuse/core';
import { useAuth } from '@/contexts/auth';
const $route = useRoute();
useTitle($route.meta.title);
// 获取用户认证状态
const { currentUser } = useAuth()
// 用户名
const username = ref('');
// 获取用户信息
onMounted(async () => {
try {
const response = await getUserInfoAPI();
if (response.data) {
username.value = response.data.user.name;
}
} catch (error) {
console.error('获取用户信息失败:', error);
}
});
// 处理用户名修改
const handleUsernameChange = async () => {
if (!username.value) {
showToast('请输入新的用户名');
return;
}
try {
const { code, data } = await updateUserInfoAPI({ name: username.value });
if (code) {
// 更新auth上下文中的用户信息
currentUser.value = {
...currentUser.value,
name: username.value
};
// 更新localStorage中的用户信息
localStorage.setItem('currentUser', JSON.stringify(currentUser.value));
showToast('用户名修改成功');
}
} catch (error) {
console.error('用户名修改失败:', error);
showToast('用户名修改失败,请重试');
}
};
</script>