138 lines
6.4 KiB
Vue
138 lines
6.4 KiB
Vue
![]() |
<template>
|
|||
|
<div class="profile-view container mt-4">
|
|||
|
<h2>Мой профиль</h2>
|
|||
|
<div v-if="loading && initialLoading" class="d-flex justify-content-center my-3">
|
|||
|
<div class="spinner-border text-primary" role="status">
|
|||
|
<span class="visually-hidden">Загрузка...</span>
|
|||
|
</div>
|
|||
|
</div>
|
|||
|
<div v-if="error" class="alert alert-danger">{{ error }}</div>
|
|||
|
|
|||
|
<div v-if="profileData && !initialLoading" class="card mb-4">
|
|||
|
<div class="card-body">
|
|||
|
<h5 class="card-title">Привет, {{ profileData.name }}!</h5>
|
|||
|
<p class="card-text"><strong>ID:</strong> {{ profileData._id }}</p>
|
|||
|
<p class="card-text"><strong>Email:</strong> {{ profileData.email }}</p>
|
|||
|
<p class="card-text"><strong>Дата регистрации:</strong> {{ formatDate(profileData.createdAt) }}</p>
|
|||
|
<p v-if="profileData.dateOfBirth" class="card-text"><strong>Дата рождения:</strong> {{ formatDate(profileData.dateOfBirth) }}</p>
|
|||
|
<p v-if="profileData.gender" class="card-text"><strong>Пол:</strong> {{ profileData.gender === 'male' ? 'Мужской' : profileData.gender === 'female' ? 'Женский' : 'Другой' }}</p>
|
|||
|
<p v-if="profileData.bio" class="card-text"><strong>О себе:</strong> {{ profileData.bio }}</p>
|
|||
|
<!-- Добавь другие поля -->
|
|||
|
</div>
|
|||
|
</div>
|
|||
|
|
|||
|
<!-- Отображение фотографий пользователя -->
|
|||
|
<div v-if="profileData && profileData.photos && profileData.photos.length > 0 && !initialLoading" class="card mb-4">
|
|||
|
<div class="card-body">
|
|||
|
<h5 class="card-title">Мои фотографии</h5>
|
|||
|
<div class="row">
|
|||
|
<div v-for="photo in profileData.photos" :key="photo.public_id" class="col-md-4 mb-3">
|
|||
|
<img :src="photo.url" class="img-fluid img-thumbnail" alt="Фото пользователя">
|
|||
|
</div>
|
|||
|
</div>
|
|||
|
</div>
|
|||
|
</div>
|
|||
|
<div v-else-if="profileData && (!profileData.photos || profileData.photos.length === 0) && !initialLoading" class="alert alert-info">
|
|||
|
У вас пока нет загруженных фотографий.
|
|||
|
</div>
|
|||
|
|
|||
|
<!-- Форма редактирования профиля -->
|
|||
|
<EditProfileForm v-if="isAuthenticated && !initialLoading" />
|
|||
|
<!-- Показываем форму, если пользователь аутентифицирован и начальная загрузка завершена -->
|
|||
|
|
|||
|
<div v-if="!profileData && !initialLoading && !error" class="alert alert-warning">
|
|||
|
<p>Не удалось загрузить данные профиля. Возможно, вы не авторизованы или произошла ошибка.</p>
|
|||
|
<router-link to="/login" class="btn btn-primary">Войти</router-link>
|
|||
|
</div>
|
|||
|
</div>
|
|||
|
</template>
|
|||
|
|
|||
|
<script setup>
|
|||
|
import { ref, onMounted, computed, watch } from 'vue'; // Добавлен watch
|
|||
|
import { useAuth } from '@/auth';
|
|||
|
import api from '@/services/api';
|
|||
|
import router from '@/router';
|
|||
|
import EditProfileForm from '@/components/EditProfileForm.vue';
|
|||
|
|
|||
|
const { isAuthenticated, user: authUserFromStore, token, fetchUser } = useAuth(); // Добавлен fetchUser
|
|||
|
const profileData = ref(null);
|
|||
|
const loading = ref(true);
|
|||
|
const initialLoading = ref(true);
|
|||
|
const error = ref('');
|
|||
|
|
|||
|
const fetchProfileDataLocal = async () => {
|
|||
|
loading.value = true;
|
|||
|
error.value = '';
|
|||
|
|
|||
|
if (!isAuthenticated.value || !token.value) {
|
|||
|
error.value = "Вы не авторизованы для просмотра этой страницы.";
|
|||
|
loading.value = false;
|
|||
|
initialLoading.value = false;
|
|||
|
return;
|
|||
|
}
|
|||
|
|
|||
|
try {
|
|||
|
// Вместо прямого вызова api.getMe(), используем fetchUser из useAuth,
|
|||
|
// который обновит authUserFromStore, за которым мы будем следить.
|
|||
|
await fetchUser();
|
|||
|
// profileData.value будет обновляться через watch
|
|||
|
} catch (err) {
|
|||
|
console.error('[ProfileView] Ошибка при вызове fetchUser:', err);
|
|||
|
error.value = (err.response && err.response.data && err.response.data.message)
|
|||
|
? err.response.data.message
|
|||
|
: 'Не удалось загрузить данные профиля. Попробуйте позже.';
|
|||
|
} finally {
|
|||
|
loading.value = false;
|
|||
|
initialLoading.value = false;
|
|||
|
}
|
|||
|
};
|
|||
|
|
|||
|
// Следим за изменениями authUserFromStore и обновляем profileData
|
|||
|
watch(authUserFromStore, (newUser) => {
|
|||
|
if (newUser) {
|
|||
|
profileData.value = { ...newUser }; // Клонируем, чтобы избежать прямой мутации, если это необходимо
|
|||
|
console.log('[ProfileView] Данные профиля обновлены из authUserFromStore:', profileData.value);
|
|||
|
}
|
|||
|
}, { immediate: true, deep: true }); // immediate: true для инициализации при монтировании
|
|||
|
|
|||
|
onMounted(() => {
|
|||
|
// Если authUserFromStore уже содержит данные (например, после логина),
|
|||
|
// они будут установлены через watch immediate: true.
|
|||
|
// Если нет, или мы хотим принудительно обновить, вызываем fetchProfileDataLocal.
|
|||
|
if (!authUserFromStore.value || Object.keys(authUserFromStore.value).length === 0) {
|
|||
|
fetchProfileDataLocal();
|
|||
|
} else {
|
|||
|
// Данные уже есть, initialLoading можно установить в false
|
|||
|
// loading также, так как данные уже есть
|
|||
|
profileData.value = { ...authUserFromStore.value };
|
|||
|
loading.value = false;
|
|||
|
initialLoading.value = false;
|
|||
|
console.log('[ProfileView] Данные профиля уже были в хранилище:', profileData.value);
|
|||
|
}
|
|||
|
});
|
|||
|
|
|||
|
const formatDate = (dateString) => {
|
|||
|
if (!dateString) return '';
|
|||
|
const options = { year: 'numeric', month: 'long', day: 'numeric' };
|
|||
|
return new Date(dateString).toLocaleDateString(undefined, options);
|
|||
|
};
|
|||
|
</script>
|
|||
|
|
|||
|
<style scoped>
|
|||
|
.profile-view {
|
|||
|
max-width: 700px;
|
|||
|
margin: auto;
|
|||
|
}
|
|||
|
.spinner-border {
|
|||
|
width: 3rem;
|
|||
|
height: 3rem;
|
|||
|
}
|
|||
|
.img-thumbnail {
|
|||
|
border: 1px solid #dee2e6;
|
|||
|
padding: 0.25rem;
|
|||
|
background-color: #fff;
|
|||
|
border-radius: 0.25rem;
|
|||
|
max-width: 100%; /* Убедимся, что изображение не выходит за рамки колонки */
|
|||
|
height: auto; /* Сохраняем пропорции */
|
|||
|
}
|
|||
|
</style>
|