Files
arcticnewone/app/pages/admin/work.vue
T
virtheart 5a7ad8de11 feat: 全面升级——后台优化 / 动态配置 / 个人中心 / OSS 存储
- OSS 文件存储(RustFS / S3 v4 兼容,零依赖手写 SigV4):
  上传/列表/删除走桶 arcticnewone,/uploads 代理服务 + 本地回退;
  server/utils/sigv4.ts 纯函数 + AWS 测试向量验证
- 业务动态配置:settings 表 + /api/settings(公开) + /api/admin/settings(PATCH),
  useSiteSettings 组合式,footer/contact/tools/app.vue/侧边栏/工具页全部接入,
  后台 /admin/settings 修改前台即时生效(站点/联系/社交/工具箱/页脚/SEO)
- 后台全面优化:Admin* 设计系统(按钮/输入/表单/卡片/徽标/弹窗/确认/空态/骨架/
  分页/页头/Toast)14 组件;Dashboard 增强;各列表页搜索/筛选/批量删除/分页;
  布局与侧边栏分组;统一 toast/确认反馈
- 个人中心全新重设计:顶部资料卡 + 统计、精致化改密/删号(二次确认)、
  收藏封面网格、评论卡片、移动端适配
- deploy.sh 支持 OSS 凭据注入(NUXT_OSS_*);.env.example 更新
- 测试 17 例全过(含 SigV4 AWS 向量、settings 默认结构)
2026-08-06 18:40:17 +08:00

637 lines
23 KiB
Vue
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<script setup lang="ts">
/**
* 后台作品管理:列表(搜索/分类/状态筛选 + 前端分页)+ 新建/编辑表单。
* - 列表来自 /api/admin/works(含未发布)
* - 新建 POST /api/admin/works;编辑 PATCH /api/admin/works/[id];删除 DELETE /api/admin/works/[id]
* - tags 逗号分隔输入;gallery 多 URL 行(每行可上传)
*/
import { computed, onMounted, reactive, ref, watch } from 'vue'
import { useToastStore } from '~/stores/toast'
definePageMeta({ middleware: 'admin', layout: 'admin' })
useHead({ title: '作品管理' })
interface Work {
id?: number
slug: string
category: 'webDesign' | 'branding' | 'development'
titleZh: string
titleEn: string
descriptionZh: string
descriptionEn: string
overviewZh: string
overviewEn: string
challengeZh: string
challengeEn: string
solutionZh: string
solutionEn: string
clientZh: string
clientEn: string
durationZh: string
durationEn: string
year: string
tags: string[]
image: string | null
gallery: string[]
url: string | null
published: number
createdAt: string
updatedAt: string
}
const toast = useToastStore()
const CATEGORIES = [
{ value: 'webDesign', label: '网页设计' },
{ value: 'branding', label: '品牌设计' },
{ value: 'development', label: '程序开发' },
]
const catLabel = (c: string) => CATEGORIES.find((x) => x.value === c)?.label ?? c
/* ---------- 列表 ---------- */
const works = ref<Work[]>([])
const loading = ref(true)
const error = ref('')
const loadWorks = async () => {
loading.value = true
error.value = ''
try {
const res = await $fetch<{ works: Work[] }>('/api/admin/works')
works.value = res.works
} catch (err: any) {
error.value = err?.data?.message || '加载失败'
} finally {
loading.value = false
}
}
onMounted(loadWorks)
/* ---------- 搜索 / 筛选 / 分页 ---------- */
const keyword = ref('')
const categoryFilter = ref<'all' | Work['category']>('all')
const statusFilter = ref<'all' | 'published' | 'draft'>('all')
const filteredWorks = computed(() => {
const kw = keyword.value.trim().toLowerCase()
return works.value.filter((w) => {
if (categoryFilter.value !== 'all' && w.category !== categoryFilter.value) return false
if (statusFilter.value === 'published' && !w.published) return false
if (statusFilter.value === 'draft' && w.published) return false
if (!kw) return true
return (
w.titleZh.toLowerCase().includes(kw) ||
w.titleEn.toLowerCase().includes(kw) ||
w.slug.toLowerCase().includes(kw) ||
w.tags.some((t) => t.toLowerCase().includes(kw))
)
})
})
const pageSize = 10
const page = ref(1)
const totalPages = computed(() => Math.max(1, Math.ceil(filteredWorks.value.length / pageSize)))
const pagedWorks = computed(() => {
const p = Math.min(page.value, totalPages.value)
const start = (p - 1) * pageSize
return filteredWorks.value.slice(start, start + pageSize)
})
watch([keyword, categoryFilter, statusFilter], () => {
page.value = 1
})
const changePage = (p: number) => {
page.value = Math.min(Math.max(1, p), totalPages.value)
}
const headerSubtitle = computed(() => {
if (view.value === 'form') return editingId.value != null ? '编辑作品' : '新建作品'
return `共 ${works.value.length} 个作品`
})
/* ---------- 表单 ---------- */
const view = ref<'list' | 'form'>('list')
const editingId = ref<number | null>(null)
const saving = ref(false)
const formError = ref('')
const emptyForm = () => ({
slug: '',
category: 'webDesign' as Work['category'],
titleZh: '',
titleEn: '',
descriptionZh: '',
descriptionEn: '',
overviewZh: '',
overviewEn: '',
challengeZh: '',
challengeEn: '',
solutionZh: '',
solutionEn: '',
clientZh: '',
clientEn: '',
durationZh: '',
durationEn: '',
year: String(new Date().getFullYear()),
image: '',
gallery: [''] as string[],
url: '',
published: true,
})
const form = reactive(emptyForm())
const tagsText = ref('')
const openCreate = () => {
Object.assign(form, emptyForm())
tagsText.value = ''
editingId.value = null
formError.value = ''
view.value = 'form'
window.scrollTo({ top: 0, behavior: 'smooth' })
}
const openEdit = (w: Work) => {
if (w.id == null) {
toast.error('该条目缺少 id 字段,暂时无法编辑(后端待补)')
return
}
editingId.value = w.id
Object.assign(form, {
slug: w.slug,
category: w.category,
titleZh: w.titleZh,
titleEn: w.titleEn,
descriptionZh: w.descriptionZh,
descriptionEn: w.descriptionEn,
overviewZh: w.overviewZh,
overviewEn: w.overviewEn,
challengeZh: w.challengeZh,
challengeEn: w.challengeEn,
solutionZh: w.solutionZh,
solutionEn: w.solutionEn,
clientZh: w.clientZh,
clientEn: w.clientEn,
durationZh: w.durationZh,
durationEn: w.durationEn,
year: w.year,
image: w.image ?? '',
gallery: w.gallery.length ? [...w.gallery] : [''],
url: w.url ?? '',
published: !!w.published,
})
tagsText.value = w.tags.join(', ')
formError.value = ''
view.value = 'form'
window.scrollTo({ top: 0, behavior: 'smooth' })
}
const backToList = () => {
view.value = 'list'
window.scrollTo({ top: 0, behavior: 'smooth' })
}
const save = async () => {
formError.value = ''
if (!/^[a-z0-9-]{2,64}$/.test(form.slug)) {
formError.value = 'slug 需为 2-64 位小写字母/数字/中划线'
return
}
if (!form.titleZh.trim() || !form.titleEn.trim()) {
formError.value = '中英文标题均为必填'
return
}
saving.value = true
try {
const payload = {
slug: form.slug,
category: form.category,
titleZh: form.titleZh,
titleEn: form.titleEn,
descriptionZh: form.descriptionZh,
descriptionEn: form.descriptionEn,
overviewZh: form.overviewZh,
overviewEn: form.overviewEn,
challengeZh: form.challengeZh,
challengeEn: form.challengeEn,
solutionZh: form.solutionZh,
solutionEn: form.solutionEn,
clientZh: form.clientZh,
clientEn: form.clientEn,
durationZh: form.durationZh,
durationEn: form.durationEn,
year: form.year,
tags: tagsText.value.split(',').map((t) => t.trim()).filter(Boolean),
image: form.image || null,
gallery: form.gallery.filter((u) => u.trim()),
url: form.url.trim() || null,
published: form.published,
}
if (editingId.value != null) {
await $fetch(`/api/admin/works/${editingId.value}`, { method: 'PATCH', body: payload })
toast.success('作品已更新')
} else {
await $fetch('/api/admin/works', { method: 'POST', body: payload })
toast.success('作品已创建')
}
await loadWorks()
view.value = 'list'
} catch (err: any) {
formError.value = err?.data?.message || '保存失败'
} finally {
saving.value = false
}
}
/* ---------- 删除 ---------- */
const confirmDelete = ref<Work | null>(null)
const deleting = ref(false)
const askDelete = (w: Work) => {
if (w.id == null) {
toast.error('该条目缺少 id 字段,暂时无法删除(后端待补)')
return
}
confirmDelete.value = w
}
const doDelete = async () => {
const w = confirmDelete.value
if (!w || w.id == null) return
deleting.value = true
try {
await $fetch(`/api/admin/works/${w.id}`, { method: 'DELETE' })
toast.success(`已删除「${w.titleZh}」`)
confirmDelete.value = null
await loadWorks()
} catch (err: any) {
toast.error(err?.data?.message || '删除失败')
} finally {
deleting.value = false
}
}
/* ---------- 图集(gallery)上传 ---------- */
const galleryFileInput = ref<HTMLInputElement | null>(null)
const uploadingIndex = ref<number | null>(null)
const galleryUploading = ref(false)
const galleryError = ref('')
const pickGalleryFile = (i: number) => {
uploadingIndex.value = i
galleryFileInput.value?.click()
}
const onGalleryFile = async (e: Event) => {
const input = e.target as HTMLInputElement
const file = input.files?.[0]
input.value = ''
if (!file || uploadingIndex.value == null) return
galleryUploading.value = true
galleryError.value = ''
try {
const fd = new FormData()
fd.append('file', file)
const res = await $fetch<{ ok: boolean; url: string }>('/api/admin/upload', {
method: 'POST',
body: fd,
})
form.gallery[uploadingIndex.value] = res.url
} catch (err: any) {
galleryError.value = err?.data?.message || '上传失败'
} finally {
galleryUploading.value = false
}
}
const addGalleryRow = () => form.gallery.push('')
const removeGalleryRow = (i: number) => form.gallery.splice(i, 1)
</script>
<template>
<div>
<!-- 页头 -->
<AdminPageHeader title="作品管理" :subtitle="headerSubtitle">
<template #actions>
<AdminButton v-if="view === 'list'" size="sm" @click="openCreate">
<Icon name="ph:plus" class="w-4 h-4" /> 新建作品
</AdminButton>
<AdminButton v-else size="sm" variant="secondary" @click="backToList">
<Icon name="ph:arrow-left" class="w-4 h-4" /> 返回列表
</AdminButton>
</template>
</AdminPageHeader>
<!-- ==================== 列表视图 ==================== -->
<template v-if="view === 'list'">
<!-- 工具栏 -->
<div class="mb-5 flex flex-col sm:flex-row gap-3">
<div class="relative flex-1 sm:max-w-xs">
<Icon name="ph:magnifying-glass" class="w-4 h-4 text-gray-400 absolute left-3.5 top-1/2 -translate-y-1/2 pointer-events-none" />
<input
v-model="keyword"
type="text"
placeholder="搜索标题 / slug / 标签…"
class="w-full rounded-xl border border-gray-200 bg-white py-2.5 pl-10 pr-9 text-sm outline-none transition-all focus:border-black focus:ring-2 focus:ring-black/10"
/>
<button
v-if="keyword"
@click="keyword = ''"
class="absolute right-2.5 top-1/2 -translate-y-1/2 w-5 h-5 rounded-full text-gray-400 hover:text-gray-600 hover:bg-gray-100 flex items-center justify-center"
aria-label="清空筛选"
>
<Icon name="ph:x" class="w-3.5 h-3.5" />
</button>
</div>
<AdminSelect
v-model="categoryFilter"
:options="[
{ value: 'all', label: '全部分类' },
...CATEGORIES,
]"
class="w-full sm:w-40"
/>
<AdminSelect
v-model="statusFilter"
:options="[
{ value: 'all', label: '全部状态' },
{ value: 'published', label: '已发布' },
{ value: 'draft', label: '草稿' },
]"
class="w-full sm:w-36"
/>
</div>
<!-- 加载态 -->
<AdminCard v-if="loading">
<AdminSkeleton :rows="6" />
</AdminCard>
<!-- 错误态 -->
<AdminCard v-else-if="error">
<div class="py-10 text-center">
<Icon name="ph:warning-circle" class="w-10 h-10 text-gray-300 mx-auto mb-4" />
<p class="text-gray-500 mb-4">{{ error }}</p>
<AdminButton size="sm" @click="loadWorks">重新加载</AdminButton>
</div>
</AdminCard>
<!-- 空态 -->
<AdminEmptyState
v-else-if="!works.length"
icon="ph:image-square"
title="还没有作品"
description="点击右上角「新建作品」创建第一个。"
/>
<AdminEmptyState
v-else-if="!filteredWorks.length"
icon="ph:magnifying-glass"
title="没有匹配的作品"
description="换个关键词或筛选条件试试。"
/>
<!-- 列表 -->
<template v-else>
<div class="rounded-2xl border border-gray-100 bg-white shadow-sm overflow-hidden">
<div class="overflow-x-auto">
<table class="w-full text-sm">
<thead>
<tr class="text-left text-gray-400 border-b border-gray-100 bg-gray-50">
<th class="px-5 py-4 font-semibold text-xs uppercase tracking-wider">标题</th>
<th class="px-5 py-4 font-semibold text-xs uppercase tracking-wider">分类</th>
<th class="px-5 py-4 font-semibold text-xs uppercase tracking-wider">年份</th>
<th class="px-5 py-4 font-semibold text-xs uppercase tracking-wider">标签</th>
<th class="px-5 py-4 font-semibold text-xs uppercase tracking-wider">状态</th>
<th class="px-5 py-4 font-semibold text-xs uppercase tracking-wider text-right">操作</th>
</tr>
</thead>
<tbody class="divide-y divide-gray-50">
<tr
v-for="w in pagedWorks"
:key="w.slug"
class="hover:bg-gray-50/60 transition-colors"
>
<td class="px-5 py-4">
<div class="flex items-center gap-3">
<img
v-if="w.image"
:src="w.image"
:alt="w.titleZh"
class="w-10 h-10 rounded-lg object-cover border border-gray-100 flex-shrink-0"
/>
<div v-else class="w-10 h-10 rounded-lg bg-gray-100 flex items-center justify-center flex-shrink-0">
<Icon name="ph:image" class="w-4 h-4 text-gray-400" />
</div>
<div class="min-w-0">
<p class="font-semibold text-black truncate">{{ w.titleZh }}</p>
<p class="text-xs text-gray-400 mt-0.5 font-mono truncate">{{ w.slug }}</p>
</div>
</div>
</td>
<td class="px-5 py-4">
<AdminBadge tone="gray">{{ catLabel(w.category) }}</AdminBadge>
</td>
<td class="px-5 py-4 text-gray-600 whitespace-nowrap">{{ w.year || '-' }}</td>
<td class="px-5 py-4">
<div class="flex flex-wrap gap-1.5 max-w-[220px]">
<span
v-for="tag in w.tags.slice(0, 3)"
:key="tag"
class="px-2 py-0.5 rounded-full bg-gray-50 text-gray-500 text-xs"
>
{{ tag }}
</span>
<span v-if="w.tags.length > 3" class="text-xs text-gray-400">+{{ w.tags.length - 3 }}</span>
</div>
</td>
<td class="px-5 py-4">
<AdminBadge :tone="w.published ? 'green' : 'amber'">
<span
class="w-1.5 h-1.5 rounded-full inline-block"
:class="w.published ? 'bg-green-500' : 'bg-amber-500'"
></span>
{{ w.published ? '已发布' : '草稿' }}
</AdminBadge>
</td>
<td class="px-5 py-4">
<div class="flex items-center justify-end gap-2">
<AdminButton size="sm" variant="secondary" @click="openEdit(w)">
<Icon name="ph:pencil-simple" class="w-3.5 h-3.5" /> 编辑
</AdminButton>
<AdminButton size="sm" variant="danger" @click="askDelete(w)">
<Icon name="ph:trash" class="w-3.5 h-3.5" /> 删除
</AdminButton>
</div>
</td>
</tr>
</tbody>
</table>
</div>
</div>
<div class="mt-4">
<AdminPagination :total="filteredWorks.length" :page="page" :page-size="pageSize" @page="changePage" />
</div>
</template>
</template>
<!-- ==================== 表单视图 ==================== -->
<template v-else>
<div class="space-y-6 max-w-4xl">
<!-- 基本信息 -->
<AdminCard title="基本信息">
<div class="grid grid-cols-1 md:grid-cols-2 gap-5">
<div>
<AdminInput
v-model="form.slug"
label="slug"
required
placeholder="如 forma-digital"
:error="formError && !/^[a-z0-9-]{2,64}$/.test(form.slug) ? 'slug 需为 2-64 位小写字母/数字/中划线' : ''"
/>
<p class="mt-1 text-xs text-gray-400">2-64 位小写字母 / 数字 / 中划线,用于前台链接</p>
</div>
<AdminSelect
v-model="form.category"
label="分类"
:options="CATEGORIES"
/>
<AdminInput v-model="form.year" label="年份" placeholder="如 2026" />
<AdminInput v-model="tagsText" label="标签" placeholder="Web Design, React, E-commerce" />
<div>
<AdminInput v-model="form.url" label="外部链接(可选)" placeholder="https://… 留空则前台不显示访问按钮" />
</div>
<div>
<p class="block text-sm font-semibold text-gray-800 mb-1.5">发布状态</p>
<div class="flex items-center gap-3 mt-1">
<AdminToggle v-model="form.published" />
<span class="text-sm" :class="form.published ? 'text-green-700 font-semibold' : 'text-gray-500'">
{{ form.published ? '已发布(前台可见)' : '草稿(前台隐藏)' }}
</span>
</div>
</div>
</div>
</AdminCard>
<!-- 标题与简介 -->
<AdminCard title="标题与简介">
<div class="grid grid-cols-1 lg:grid-cols-2 gap-5">
<div class="space-y-4">
<AdminInput v-model="form.titleZh" label="中文标题" required />
<AdminTextarea v-model="form.descriptionZh" label="中文简介" :rows="3" />
</div>
<div class="space-y-4">
<AdminInput v-model="form.titleEn" label="English Title" required />
<AdminTextarea v-model="form.descriptionEn" label="English Description" :rows="3" />
</div>
</div>
</AdminCard>
<!-- 项目详情(中英) -->
<AdminCard title="项目详情(中英各一组)">
<div class="space-y-6">
<div class="grid grid-cols-1 lg:grid-cols-2 gap-5">
<div class="space-y-4">
<AdminTextarea v-model="form.overviewZh" label="中文概述(Overview)" :rows="4" />
<AdminTextarea v-model="form.challengeZh" label="中文挑战(Challenge)" :rows="3" />
<AdminTextarea v-model="form.solutionZh" label="中文方案(Solution)" :rows="3" />
</div>
<div class="space-y-4">
<AdminTextarea v-model="form.overviewEn" label="English Overview" :rows="4" />
<AdminTextarea v-model="form.challengeEn" label="English Challenge" :rows="3" />
<AdminTextarea v-model="form.solutionEn" label="English Solution" :rows="3" />
</div>
</div>
<div class="grid grid-cols-1 lg:grid-cols-2 gap-5">
<AdminInput v-model="form.clientZh" label="中文客户(Client)" />
<AdminInput v-model="form.clientEn" label="English Client" />
<AdminInput v-model="form.durationZh" label="中文周期(Duration)" placeholder="如 3 个月" />
<AdminInput v-model="form.durationEn" label="English Duration" placeholder="如 3 months" />
</div>
</div>
</AdminCard>
<!-- 封面图 -->
<AdminCard title="封面图">
<AdminImageUpload v-model="form.image" label="封面图" />
</AdminCard>
<!-- 作品图集 -->
<AdminCard>
<template #actions>
<AdminButton size="sm" variant="secondary" @click="addGalleryRow">
<Icon name="ph:plus" class="w-3.5 h-3.5" /> 添加图片
</AdminButton>
</template>
<template #default>
<div class="space-y-3">
<div
v-for="(url, i) in form.gallery"
:key="i"
class="flex items-center gap-3 border border-gray-200 rounded-xl bg-white p-3"
>
<div class="flex-1 min-w-0">
<input
v-model="form.gallery[i]"
type="text"
placeholder="图片 URL(本地 /uploads/... 或 https://...)"
class="w-full px-3 py-2 rounded-lg border border-gray-200 bg-gray-50 text-sm outline-none transition-all focus:border-black focus:bg-white"
/>
<div v-if="url" class="mt-2">
<img :src="url" alt="图集预览" class="h-24 w-auto max-w-full rounded-lg border border-gray-100 object-cover" />
</div>
</div>
<button
type="button"
:disabled="galleryUploading && uploadingIndex === i"
@click="pickGalleryFile(i)"
class="flex items-center gap-1.5 px-3 py-2 rounded-lg bg-black text-white text-xs font-semibold hover:bg-gray-800 transition-colors disabled:opacity-60 flex-shrink-0"
>
<Icon
:name="galleryUploading && uploadingIndex === i ? 'ph:circle-notch' : 'ph:upload-simple'"
:class="galleryUploading && uploadingIndex === i ? 'w-3.5 h-3.5 animate-spin' : 'w-3.5 h-3.5'"
/>
{{ galleryUploading && uploadingIndex === i ? '上传中…' : '上传' }}
</button>
<button
type="button"
@click="removeGalleryRow(i)"
class="w-8 h-8 rounded-lg hover:bg-red-50 text-gray-400 hover:text-red-600 flex items-center justify-center transition-colors flex-shrink-0"
aria-label="删除该图"
>
<Icon name="ph:trash" class="w-4 h-4" />
</button>
</div>
<p v-if="galleryError" class="text-xs text-red-600">{{ galleryError }}</p>
</div>
<input ref="galleryFileInput" type="file" accept="image/*" class="hidden" @change="onGalleryFile" />
</template>
</AdminCard>
<!-- 提交 -->
<div class="flex items-center justify-end gap-3">
<p v-if="formError" class="mr-auto text-sm text-red-600">{{ formError }}</p>
<AdminButton variant="secondary" @click="backToList">取消</AdminButton>
<AdminButton :loading="saving" @click="save">
{{ saving ? '保存中…' : editingId != null ? '保存修改' : '创建作品' }}
</AdminButton>
</div>
</div>
</template>
<!-- 删除确认 -->
<AdminConfirm
:open="!!confirmDelete"
:loading="deleting"
danger
:message="`确定要删除「${confirmDelete?.titleZh}」吗?该作品下的所有收藏将一并删除,此操作不可撤销。`"
@update:open="confirmDelete = null"
@confirm="doDelete"
/>
</div>
</template>