优化页面、修复BUG

This commit is contained in:
李琦
2026-06-24 16:50:04 +08:00
parent 88ba9be318
commit 3f653bc336
36 changed files with 1672 additions and 2401 deletions

View File

@@ -10,10 +10,21 @@
<input
type="text"
v-model="searchQuery"
@focus="handleSearchFocus"
@blur="handleSearchBlur"
@keyup.enter="handleSearch"
placeholder="搜索文章标题或内容..."
class="w-full bg-white/5 border border-white/10 rounded-full px-6 py-3 text-white placeholder-white/30 focus:outline-none focus:border-art-accent transition-colors"
/>
<SearchSuggestDropdown
:visible="showSearchSuggest"
:history="searchHistory"
:hot-keywords="hotKeywords"
:loading-hot="loadingHot"
@select="selectSuggestKeyword"
@remove-history="removeSearchHistoryItem"
@clear-history="clearSearchHistory"
/>
<button
v-if="searchQuery"
@click="clearSearch"
@@ -129,9 +140,13 @@
<script setup lang="ts">
import { ref, onMounted, nextTick, computed, onBeforeUnmount } from 'vue'
import { fetchPosts, fetchCategories, fetchTags, getPublicSettings, Post, Category, Tag, PaginationResponse } from '../services/api'
import { fetchPosts, fetchCategories, fetchTags, getPublicSettings, getHotSearches, Post, Category, Tag, PaginationResponse, HotSearchKeyword } from '../services/api'
import { useScrollAnimation } from '../composables/useScrollAnimation'
import { useSearchHistory } from '../composables/useSearchHistory'
import CustomSelect from '../components/CustomSelect.vue'
import SearchSuggestDropdown from '../components/SearchSuggestDropdown.vue'
const { getHistory, addHistory, removeHistory, clearHistory } = useSearchHistory()
const blogPosts = ref<Post[]>([])
const loading = ref(false)
@@ -142,6 +157,11 @@ const selectedCategoryId = ref(0)
const selectedTagId = ref(0)
const categories = ref<Category[]>([])
const tags = ref<Tag[]>([])
const showSearchSuggest = ref(false)
const searchHistory = ref<string[]>([])
const hotKeywords = ref<HotSearchKeyword[]>([])
const loadingHot = ref(false)
let blurTimer: ReturnType<typeof setTimeout> | null = null
// 分页相关状态
const currentPage = ref(1)
@@ -262,9 +282,54 @@ const removeScrollListener = () => {
const handleSearch = () => {
if (!searchQuery.value.trim() && !isSearching.value) return
isSearching.value = !!searchQuery.value.trim()
if (searchQuery.value.trim()) {
addHistory(searchQuery.value.trim())
searchHistory.value = getHistory()
}
showSearchSuggest.value = false
fetchBlogPosts(true)
}
const handleSearchFocus = async () => {
if (blurTimer) {
clearTimeout(blurTimer)
blurTimer = null
}
searchHistory.value = getHistory()
showSearchSuggest.value = true
if (hotKeywords.value.length === 0 && !loadingHot.value) {
loadingHot.value = true
try {
hotKeywords.value = await getHotSearches()
} catch (err) {
console.error('Failed to load hot searches:', err)
} finally {
loadingHot.value = false
}
}
}
const handleSearchBlur = () => {
blurTimer = setTimeout(() => {
showSearchSuggest.value = false
}, 150)
}
const selectSuggestKeyword = (keyword: string) => {
searchQuery.value = keyword
handleSearch()
}
const removeSearchHistoryItem = (keyword: string) => {
removeHistory(keyword)
searchHistory.value = getHistory()
}
const clearSearchHistory = () => {
clearHistory()
searchHistory.value = []
}
const clearSearch = () => {
searchQuery.value = ''
isSearching.value = false

View File

@@ -106,10 +106,12 @@
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import { useToast } from '../composables/useToast'
import { useAuth } from '../composables/useAuth'
import { login } from '../services/api'
const router = useRouter()
const toast = useToast()
const { login: saveAuth } = useAuth()
const form = ref({
username: '',
@@ -125,9 +127,7 @@ const handleLogin = async () => {
try {
const response = await login(form.value)
// 保存token到本地存储
localStorage.setItem('token', response.token)
localStorage.setItem('user', JSON.stringify(response.user))
saveAuth(response.token, response.user, response.expire)
toast.showToast('欢迎回来,管理员', 'success')
// 登录成功后重定向到管理后台
router.push('/admin')

View File

@@ -53,6 +53,21 @@
<div v-if="attachment.fileType === 'image'" class="aspect-square mb-2 rounded overflow-hidden bg-white/5">
<img :src="attachment.fileUrl" :alt="attachment.originalName" class="w-full h-full object-cover" />
</div>
<div v-else-if="attachment.fileType === 'video'" class="aspect-square mb-2 rounded overflow-hidden bg-black/40 relative">
<video
:src="attachment.fileUrl"
muted
preload="metadata"
class="w-full h-full object-cover"
/>
<div class="absolute inset-0 flex items-center justify-center bg-black/30 pointer-events-none">
<div class="w-10 h-10 rounded-full bg-white/20 backdrop-blur-sm flex items-center justify-center border border-white/30">
<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="white">
<polygon points="8 5 19 12 8 19 8 5"></polygon>
</svg>
</div>
</div>
</div>
<div v-else class="aspect-square mb-2 rounded bg-white/5 flex items-center justify-center">
<i data-lucide="file" class="w-12 h-12 text-art-muted"></i>
</div>
@@ -135,7 +150,7 @@ import { ref, onMounted, computed } from 'vue'
import { useToast } from '../../composables/useToast'
import CustomSelect from '../../components/CustomSelect.vue'
import AttachmentDetailModal from '../../components/admin/AttachmentDetailModal.vue'
import { updateAttachment, type Attachment } from '../../services/api'
import { updateAttachment, type Attachment, API_BASE, authFetch, parseApiResponse } from '../../services/api'
const toast = useToast()
@@ -191,14 +206,6 @@ const uploadCategoryOptions = computed(() => {
})
const API_BASE = '/api'
const getAuthHeaders = () => {
const token = localStorage.getItem('token')
return {
...(token ? { Authorization: `Bearer ${token}` } : {})
}
}
const loadAttachments = async () => {
loading.value = true
try {
@@ -210,14 +217,8 @@ const loadAttachments = async () => {
url += `&fileType=${filterFileType.value}`
}
const response = await fetch(url, {
headers: getAuthHeaders()
})
if (!response.ok) throw new Error('获取附件列表失败')
const data = await response.json()
attachments.value = data.result.list || []
const data = await parseApiResponse<{ list: Attachment[] }>(await authFetch(url))
attachments.value = data?.list || []
} catch (err: any) {
toast.showToast(err.message || '加载失败', 'error')
} finally {
@@ -227,14 +228,8 @@ const loadAttachments = async () => {
const loadCategories = async () => {
try {
const response = await fetch(`${API_BASE}/admin/attachment-categories`, {
headers: getAuthHeaders()
})
if (!response.ok) throw new Error('获取分类失败')
const data = await response.json()
categories.value = data.result || []
const data = await parseApiResponse<Category[]>(await authFetch(`${API_BASE}/admin/attachment-categories`))
categories.value = data || []
} catch (err) {
console.error('Failed to load categories:', err)
}
@@ -259,16 +254,11 @@ const uploadFile = async () => {
}
formData.append('storageType', 'local')
const response = await fetch(`${API_BASE}/admin/attachments/upload`, {
await parseApiResponse(await authFetch(`${API_BASE}/admin/attachments/upload`, {
method: 'POST',
headers: getAuthHeaders(),
headers: {},
body: formData
})
if (!response.ok) {
const errorData = await response.json()
throw new Error(errorData.message || '上传失败')
}
}))
toast.showToast('上传成功', 'success')
showUploadModal.value = false
@@ -286,12 +276,9 @@ const deleteAttachment = async (id: number) => {
if (!confirm('确定要删除这个附件吗?')) return
try {
const response = await fetch(`${API_BASE}/admin/attachments/${id}`, {
method: 'DELETE',
headers: getAuthHeaders()
})
if (!response.ok) throw new Error('删除失败')
await parseApiResponse(await authFetch(`${API_BASE}/admin/attachments/${id}`, {
method: 'DELETE'
}))
toast.showToast('删除成功', 'success')
loadAttachments()

View File

@@ -64,7 +64,7 @@
<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { API_BASE, getAuthHeaders, type EmailSuffix } from '../../services/api'
import { API_BASE, authFetchJson, getAuthHeaders, type EmailSuffix } from '../../services/api'
import { useToast } from '../../composables/useToast'
const toast = useToast()
@@ -74,13 +74,9 @@ const newSortOrder = ref(0)
const fetchSuffixes = async () => {
try {
const response = await fetch(`${API_BASE}/admin/email-suffixes`, {
suffixes.value = await authFetchJson<EmailSuffix[]>(`${API_BASE}/admin/email-suffixes`, {
headers: getAuthHeaders()
})
if (response.ok) {
const data = await response.json()
suffixes.value = data.result || []
}
}) || []
} catch (error) {
console.error('Failed to fetch suffixes:', error)
}
@@ -93,7 +89,7 @@ const handleAdd = async () => {
}
try {
const response = await fetch(`${API_BASE}/admin/email-suffixes`, {
await authFetchJson(`${API_BASE}/admin/email-suffixes`, {
method: 'POST',
headers: getAuthHeaders(),
body: JSON.stringify({
@@ -102,19 +98,13 @@ const handleAdd = async () => {
sortOrder: newSortOrder.value
})
})
if (response.ok) {
toast.success('添加成功')
newSuffix.value = ''
newSortOrder.value = 0
fetchSuffixes()
} else {
const errorData = await response.json()
toast.error(errorData.message || '添加失败')
}
} catch (error) {
toast.success('添加成功')
newSuffix.value = ''
newSortOrder.value = 0
fetchSuffixes()
} catch (error: any) {
console.error(error)
toast.error('添加失败')
toast.error(error.message || '添加失败')
}
}
@@ -122,21 +112,15 @@ const handleDelete = async (id: number) => {
if (!confirm('确定删除该后缀吗?')) return
try {
const response = await fetch(`${API_BASE}/admin/email-suffixes/${id}`, {
await authFetchJson(`${API_BASE}/admin/email-suffixes/${id}`, {
method: 'DELETE',
headers: getAuthHeaders()
})
if (response.ok) {
toast.success('删除成功')
fetchSuffixes()
} else {
const errorData = await response.json()
toast.error(errorData.message || '删除失败')
}
} catch (error) {
toast.success('删除成功')
fetchSuffixes()
} catch (error: any) {
console.error(error)
toast.error('删除失败')
toast.error(error.message || '删除失败')
}
}

View File

@@ -74,21 +74,15 @@
<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { API_BASE, getAuthHeaders, type Inquiry } from '../../services/api'
import { API_BASE, authFetchJson, fetchInquiries, getAuthHeaders, type Inquiry } from '../../services/api'
import { useToast } from '../../composables/useToast'
const toast = useToast()
const inquiries = ref<Inquiry[]>([])
const fetchInquiries = async () => {
const fetchInquiriesList = async () => {
try {
const response = await fetch(`${API_BASE}/admin/inquiries`, {
headers: getAuthHeaders()
})
if (response.ok) {
const data = await response.json()
inquiries.value = data.result || []
}
inquiries.value = await fetchInquiries()
} catch (error) {
console.error('Failed to fetch inquiries:', error)
toast.error('获取咨询列表失败')
@@ -97,22 +91,16 @@ const fetchInquiries = async () => {
const updateStatus = async (id: number, status: number) => {
try {
const response = await fetch(`${API_BASE}/admin/inquiries/${id}/status`, {
await authFetchJson(`${API_BASE}/admin/inquiries/${id}/status`, {
method: 'PUT',
headers: getAuthHeaders(),
body: JSON.stringify({ status })
})
if (response.ok) {
toast.success('状态更新成功')
fetchInquiries()
} else {
const errorData = await response.json()
toast.error(errorData.message || '更新失败')
}
} catch (error) {
toast.success('状态更新成功')
fetchInquiriesList()
} catch (error: any) {
console.error(error)
toast.error('更新失败')
toast.error(error.message || '更新失败')
}
}
@@ -144,7 +132,7 @@ const getStatusClass = (status?: number) => {
}
onMounted(() => {
fetchInquiries()
fetchInquiriesList()
})
</script>

View File

@@ -17,6 +17,15 @@
</button>
</div>
<div class="flex gap-3">
<button
v-if="isEditing"
type="button"
class="admin-btn-secondary"
@click="openHistoryModal"
title="查看历史版本"
>
📜 历史版本
</button>
<button
v-if="isEditing"
type="button"
@@ -40,14 +49,17 @@
<div class="flex-1 flex flex-col min-w-0 transition-all duration-300 ease-in-out h-full">
<div
class="admin-card flex-1 flex flex-col overflow-hidden border border-white/10 focus-within:border-art-accent/50 transition-colors"
@paste="handlePaste"
@paste="handleVideoPaste"
>
<MdEditor
ref="editorRef"
v-model="form.content"
theme="dark"
:preview="false"
placeholder="开始创作..."
class="custom-md-editor flex-1"
@onUploadImg="handleUploadImg"
@onDrop="handleEditorDrop"
/>
</div>
</div>
@@ -251,6 +263,13 @@
</form>
<!-- Access Log Modal -->
<PostHistoryModal
v-if="isEditing"
:is-open="isHistoryModalOpen"
:post-id="route.params.id as string"
@close="isHistoryModalOpen = false"
@restored="loadData"
/>
<AccessLogModal
v-if="isEditing"
v-model:isOpen="isAccessLogModalOpen"
@@ -265,6 +284,7 @@ import { ref, reactive, onMounted, computed } from 'vue'
import { useRouter, useRoute } from 'vue-router'
// 引入 md-editor-v3
import { MdEditor } from 'md-editor-v3'
import type { ExposeParam, UploadImgCallBack } from 'md-editor-v3'
import 'md-editor-v3/lib/style.css'
import { useToast } from '../../composables/useToast'
@@ -280,8 +300,10 @@ import {
createTag as createTagApi,
Tag
} from '../../services/api'
import { authFetch, parseApiResponse } from '../../services/api'
import CustomSelect from '../../components/CustomSelect.vue'
import AccessLogModal from '../../components/admin/AccessLogModal.vue'
import PostHistoryModal from '../../components/admin/PostHistoryModal.vue'
import ImageUpload from '../../components/admin/ImageUpload.vue'
const router = useRouter()
@@ -301,9 +323,13 @@ const errors = reactive<Record<string, string>>({})
// Access log modal state
const isAccessLogModalOpen = ref(false)
const isHistoryModalOpen = ref(false)
const openAccessLogModal = () => {
isAccessLogModalOpen.value = true
}
const openHistoryModal = () => {
isHistoryModalOpen.value = true
}
// Data sources
const categories = ref<{value: number, label: string}[]>([])
@@ -517,67 +543,96 @@ const handleCancel = () => {
router.push('/admin/posts')
}
// Handle paste event for image upload
const handlePaste = async (e: ClipboardEvent) => {
const editorRef = ref<ExposeParam>()
const uploadMediaFile = async (file: File): Promise<string | null> => {
const formData = new FormData()
formData.append('file', file)
formData.append('categoryId', '1')
formData.append('storageType', 'local')
const response = await authFetch('/api/admin/attachments/upload', {
method: 'POST',
headers: {},
body: formData
})
const result = await parseApiResponse<{ fileUrl: string }>(response)
return result?.fileUrl ?? null
}
const insertAtCursor = (text: string) => {
editorRef.value?.insert?.(() => ({ targetValue: text }))
}
const uploadAndInsertVideo = async (file: File) => {
try {
const url = await uploadMediaFile(file)
if (!url) return
insertAtCursor(`\n<video controls src="${url}" style="max-width:100%"></video>\n`)
toast.showToast('视频上传成功', 'success')
} catch (error: any) {
console.error('上传视频失败:', error)
toast.showToast(error.message || '上传视频失败', 'error')
}
}
const handleUploadImg = async (files: File[], callback: UploadImgCallBack) => {
try {
const uploadResults = await Promise.all(
files.map(async (file) => {
const url = await uploadMediaFile(file)
return url ? { url, alt: file.name, title: file.name } : null
})
)
const urls = uploadResults.filter((item): item is { url: string; alt: string; title: string } => item !== null)
if (urls.length > 0) {
callback(urls)
toast.showToast('图片上传成功', 'success')
}
} catch (error: any) {
console.error('上传图片失败:', error)
toast.showToast(error.message || '上传图片失败', 'error')
}
}
const handleEditorDrop = async (e: DragEvent) => {
const files = Array.from(e.dataTransfer?.files || [])
const imageFiles = files.filter((f) => f.type.startsWith('image/'))
const videoFiles = files.filter((f) => f.type.startsWith('video/'))
if (imageFiles.length === 0 && videoFiles.length === 0) return
e.preventDefault()
if (imageFiles.length > 0) {
await handleUploadImg(imageFiles, (urls) => {
if (!Array.isArray(urls) || urls.length === 0) return
urls.forEach((item) => {
if (typeof item === 'string') {
insertAtCursor(`![image](${item})`)
} else {
insertAtCursor(`![${item.alt || 'image'}](${item.url})`)
}
})
})
}
for (const file of videoFiles) {
await uploadAndInsertVideo(file)
}
}
const handleVideoPaste = async (e: ClipboardEvent) => {
const items = e.clipboardData?.items
if (!items) return
// Check if any item is an image
let hasImage = false
for (let i = 0; i < items.length; i++) {
if (items[i].type.startsWith('image/')) {
hasImage = true
break
}
}
if (!hasImage) return
// Prevent default paste behavior for images
e.preventDefault()
for (let i = 0; i < items.length; i++) {
const item = items[i]
if (item.type.startsWith('image/')) {
if (item.type.startsWith('video/')) {
e.preventDefault()
const file = item.getAsFile()
if (!file) continue
try {
// Upload image
const formData = new FormData()
formData.append('file', file)
formData.append('categoryId', '1') // 默认上传到分类1
formData.append('storageType', 'local')
const token = localStorage.getItem('token')
const response = await fetch('/api/admin/attachments/upload', {
method: 'POST',
headers: {
...(token ? { Authorization: `Bearer ${token}` } : {})
},
body: formData
})
if (!response.ok) {
const errorData = await response.json()
throw new Error(errorData.message || '上传失败')
}
const data = await response.json()
const imageUrl = data.result.fileUrl
// Insert markdown image syntax
const imageMarkdown = `![${file.name}](${imageUrl})`
const currentContent = form.content
// Insert at the end of content (md-editor-v3 will handle cursor position)
form.content = currentContent + (currentContent ? '\n\n' : '') + imageMarkdown + '\n'
toast.showToast('图片上传成功', 'success')
} catch (error: any) {
console.error('上传图片失败:', error)
toast.showToast(error.message || '上传图片失败', 'error')
}
break // Only handle first image
if (file) await uploadAndInsertVideo(file)
break
}
}
}

View File

@@ -78,7 +78,7 @@
import { ref, reactive, onMounted, computed } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { useToast } from '../../composables/useToast'
import { createUser, updateUser, API_BASE, getAuthHeaders } from '../../services/api'
import { createUser, updateUser, fetchUser } from '../../services/api'
import CustomSelect from '../../components/CustomSelect.vue'
const router = useRouter()
@@ -180,49 +180,13 @@ onMounted(async () => {
if (isEditing.value) {
try {
const userId = parseInt(route.params.id as string)
console.log(`Fetching user data for ID: ${userId}`)
// Direct fetch to debug
const response = await fetch(`${API_BASE}/admin/users/${userId}`, {
headers: getAuthHeaders()
})
console.log(`Response status: ${response.status}`)
// Check response headers
const contentType = response.headers.get('content-type')
console.log(`Response content-type: ${contentType}`)
// Read response as text first to debug
const responseText = await response.text()
console.log(`Response text: ${responseText}`)
// Then try to parse as JSON
if (!response.ok) {
// If response is not ok, still try to parse as JSON
let errorData
try {
errorData = JSON.parse(responseText)
throw new Error(errorData.message || '获取用户详情失败')
} catch (parseError) {
const errorMessage = parseError instanceof Error ? parseError.message : String(parseError)
throw new Error(`获取用户详情失败,响应格式错误: ${errorMessage}`)
}
}
// Parse successful response
const data = JSON.parse(responseText)
const user = data.result // 从统一响应格式中提取 result
console.log('Parsed user data:', user)
// Populate form with user data
const user = await fetchUser(userId)
form.username = user.username
form.email = user.email
form.role = user.role
form.isActive = user.isActive
} catch (error: any) {
console.error('Failed to fetch user data:', error)
console.error('Error stack:', error.stack)
toast.error('加载用户数据失败: ' + (error.message || '未知错误'))
}
}