fix(profile): 修复头像选择后实时预览不更新

改用 computed 属性 avatarSrc 计算头像显示源,
优先级:本地预览(pendingAvatarFile) > 已保存头像(userInfo.avatar)
This commit is contained in:
小蟑螂
2026-03-29 15:23:36 +08:00
parent f3a0309dbd
commit fe2d93864b
@@ -1,7 +1,7 @@
<script lang="ts" setup>
import type { UserVO } from '#/api/system/user/types';
import { reactive, ref } from 'vue';
import { computed, reactive, ref } from 'vue';
import { Page } from '@vben/common-ui';
@@ -19,7 +19,17 @@ const avatarLoading = ref(false);
// 待上传的头像文件(用户选择后先缓存,保存时再上传)
const pendingAvatarFile = ref<File | null>(null);
const previewAvatarUrl = ref<string | null>(null);
// 计算属性:头像显示优先级:本地预览 > 已保存的头像 > 初始头像
const avatarSrc = computed(() => {
if (pendingAvatarFile.value) {
return URL.createObjectURL(pendingAvatarFile.value);
}
if (userInfo.value?.avatar) {
return userInfo.value.avatar;
}
return null;
});
// 表单数据
const formData = reactive({
@@ -41,8 +51,7 @@ async function fetchUserInfo() {
formData.realName = data.realName || '';
formData.phone = data.phone || '';
formData.remark = data.remark || '';
// 重置头像预览
previewAvatarUrl.value = null;
// 重置待上传的头像
pendingAvatarFile.value = null;
} catch (error) {
console.error('获取用户信息失败:', error);
@@ -65,9 +74,8 @@ async function handleAvatarChange(info: any) {
return false;
}
// 缓存头像文件,预览用本地 URL
// 缓存头像文件,预览由 computed avatarSrc 自动处理
pendingAvatarFile.value = file;
previewAvatarUrl.value = URL.createObjectURL(file);
return false; // 阻止默认上传
}
@@ -112,7 +120,6 @@ function handleReset() {
formData.remark = userInfo.value.remark || '';
}
formRef.value?.resetFields();
previewAvatarUrl.value = null;
pendingAvatarFile.value = null;
}
@@ -156,8 +163,8 @@ fetchUserInfo();
class="absolute inset-0 flex items-center justify-center bg-white/80 z-10"
/>
<img
v-if="previewAvatarUrl || userInfo?.avatar"
:src="previewAvatarUrl || userInfo?.avatar"
v-if="avatarSrc"
:src="avatarSrc"
alt="头像"
class="h-24 w-24 rounded-full object-cover"
/>