Files
JayuCloud/Frontend/src/views/ProductListView.vue
T

506 lines
12 KiB
Vue
Raw Normal View History

<template>
<div class="mobile-container">
<header class="header">
<a-button class="back-btn" type="text" @click="handleBackClick">
<LeftOutlined :style="{ fontSize: '20px' }" />
</a-button>
2026-03-05 16:08:27 +08:00
<h1 v-if="!showSearch">作品列表</h1>
2026-03-05 16:02:34 +08:00
<div v-else class="search-input-container">
<a-input-search
v-model:value="searchKeyword"
2026-03-05 16:08:27 +08:00
placeholder="搜索作品"
2026-03-05 16:02:34 +08:00
class="search-input"
enter-button
@search="handleSearch"
2026-03-05 16:02:34 +08:00
/>
</div>
<a-button class="search-btn" type="text" @click="toggleSearch">
<SearchOutlined :style="{ fontSize: '20px' }" />
</a-button>
</header>
<div class="main-content">
<div class="category-sidebar">
<div
v-for="category in categories"
:key="category"
class="category-item"
:class="{ active: selectedCategory === category }"
@click="handleCategoryClick(category)"
>
{{ category }}
</div>
</div>
<div class="product-section">
<a-alert
v-if="activeBannerText"
class="page-banner"
type="info"
show-icon
:message="activeBannerText"
/>
<div class="product-grid">
<a-card
v-for="item in products"
:key="item.id"
class="product-card"
:body-style="{ padding: '12px' }"
hoverable
@click="handleProductClick(item)"
>
2026-02-24 09:59:22 +08:00
<div class="product-img">
<img
v-if="getProductImages(item).length > 0"
:src="getProductImages(item)[0]"
:alt="item.title || item.name"
2026-02-24 09:59:22 +08:00
class="product-image"
/>
<div v-else class="product-img-placeholder">
<span>{{ (item.title || item.name)?.[0] || '作' }}</span>
2026-02-24 09:59:22 +08:00
</div>
</div>
2026-02-24 09:59:22 +08:00
<div class="product-info">
<p class="name">{{ item.title || item.name }}</p>
2026-02-24 09:59:22 +08:00
<div class="product-meta">
<span class="duration">{{ item.approximateDuration || '时长待定' }}</span>
2026-02-24 09:59:22 +08:00
<div class="stats">
<span>{{ item.likeCount || 0 }} 点赞</span>
<span>{{ item.collectCount || 0 }} 收藏</span>
2026-02-24 09:59:22 +08:00
</div>
</div>
2026-02-24 09:59:22 +08:00
<div class="product-tags">
<template v-if="item.tagInfos?.length">
<a-tag
v-for="tag in item.tagInfos"
:key="tag.id"
size="small"
:style="{
marginRight: '4px',
marginBottom: '4px',
color: tag.textColor || '#333',
backgroundColor: tag.bgColor || '#f0f0f0',
borderColor: tag.borderColor || '#f0f0f0'
}"
>
{{ tag.tagName }}
</a-tag>
</template>
<a-tag v-else size="small" color="default">暂无标签</a-tag>
2026-02-24 09:59:22 +08:00
</div>
2026-02-24 09:59:22 +08:00
<div class="price-row">
<p class="price">¥{{ Number(item.price || 0).toFixed(2) }}</p>
<a-button
type="primary"
size="small"
2026-02-24 09:59:22 +08:00
shape="circle"
@click.stop="handleAddToCart(item)"
>
<ShoppingCartOutlined />
</a-button>
</div>
</div>
</a-card>
</div>
2026-02-24 09:59:22 +08:00
<div v-if="products.length === 0 && !loading" class="empty-state">
<a-empty description="暂时没有匹配的作品">
<a-button type="primary" @click="resetFilters">查看全部作品</a-button>
</a-empty>
2026-02-24 09:59:22 +08:00
</div>
<div v-if="loading" class="loading-state">
<a-spin />
2026-02-24 09:59:22 +08:00
</div>
</div>
</div>
</div>
</template>
<script setup lang="ts">
import { onMounted, ref, watch, inject, computed } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { LeftOutlined, SearchOutlined, ShoppingCartOutlined } from '@ant-design/icons-vue'
import { message } from 'ant-design-vue'
2026-02-24 09:59:22 +08:00
import { productApi, type ProductVO } from '@/api/product'
import { tagApi, type TagVO } from '@/api/tag'
import { cartApi } from '@/api/cart'
import { fileApi } from '@/api/file'
const router = useRouter()
const route = useRoute()
2026-03-19 20:51:07 +08:00
const updateCartCount = inject<() => Promise<void>>('updateCartCount', async () => {})
2026-03-05 16:28:05 +08:00
2026-02-24 09:59:22 +08:00
const allTags = ref<TagVO[]>([])
2026-02-24 11:34:25 +08:00
const categories = ref<string[]>(['全部'])
const selectedCategory = ref('全部')
2026-02-24 09:59:22 +08:00
const products = ref<ProductVO[]>([])
const loading = ref(false)
2026-03-05 16:02:34 +08:00
const showSearch = ref(false)
const searchKeyword = ref('')
const imageIdCache = ref<Record<string, string>>({})
const imageUrls = ref<Record<number, string[]>>({})
2026-02-26 11:16:24 +08:00
const isLoggedIn = computed(() => Boolean(localStorage.getItem('accessToken') || sessionStorage.getItem('accessToken')))
const activeBannerText = computed(() => {
if (searchKeyword.value.trim()) {
return `当前显示“${searchKeyword.value.trim()}”的搜索结果`
}
if (selectedCategory.value !== '全部') {
return `当前按标签“${selectedCategory.value}”筛选`
}
return ''
})
const DEFAULT_PRODUCT_IMAGE = 'data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMjAwIiBoZWlnaHQ9IjIwMCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48cmVjdCBmaWxsPSIjZjVmNWY1IiB3aWR0aD0iMjAwIiBoZWlnaHQ9IjIwMCIvPjx0ZXh0IHg9IjUwJSIgeT0iNTAlIiBmaWxsPSIjYmZiZmJmIiBmb250LXNpemU9IjI0IiB0ZXh0LWFuY2hvcj0ibWlkZGxlIiBkeT0iLjNlbSI+YWFhPC90ZXh0Pjwvc3ZnPg=='
const ensureLoginForAction = (actionText: string) => {
if (isLoggedIn.value) {
return true
}
message.info(`${actionText}前请先登录账号`)
router.push('/')
return false
}
const loadImageUrls = async (productList: ProductVO[]) => {
for (const product of productList) {
if (!product.imageFileIds) {
imageUrls.value[product.id] = [DEFAULT_PRODUCT_IMAGE]
continue
}
const ids = product.imageFileIds.split(',').map(id => id.trim()).filter(Boolean)
const urls: string[] = []
for (const id of ids) {
try {
if (!imageIdCache.value[id]) {
imageIdCache.value[id] = await fileApi.getSignedUrl(Number(id)) as unknown as string
}
if (imageIdCache.value[id]) {
urls.push(imageIdCache.value[id])
}
} catch (error) {
console.error('获取作品图片失败:', error)
}
}
imageUrls.value[product.id] = urls.length ? urls : [DEFAULT_PRODUCT_IMAGE]
}
}
const getProductImages = (product: ProductVO): string[] => imageUrls.value[product.id] || [DEFAULT_PRODUCT_IMAGE]
2026-02-24 09:59:22 +08:00
const fetchTags = async () => {
try {
const response = await tagApi.getAllTags() as unknown as TagVO[]
allTags.value = Array.isArray(response) ? response : []
2026-02-24 11:34:25 +08:00
categories.value = ['全部', ...allTags.value.map(tag => tag.tagName)]
2026-02-24 09:59:22 +08:00
} catch (error) {
console.error('获取标签失败:', error)
categories.value = ['全部']
2026-02-24 09:59:22 +08:00
}
}
const fetchProducts = async () => {
loading.value = true
try {
let response: ProductVO[] = []
const keyword = searchKeyword.value.trim()
if (keyword) {
response = await productApi.searchProducts(keyword)
} else if (selectedCategory.value === '全部') {
response = await productApi.getAllProducts()
2026-02-24 09:59:22 +08:00
} else {
response = await productApi.getProductsByTag(selectedCategory.value)
2026-02-24 09:59:22 +08:00
}
products.value = Array.isArray(response) ? response : []
await loadImageUrls(products.value)
2026-02-24 09:59:22 +08:00
} catch (error) {
console.error('获取作品列表失败:', error)
message.error('加载作品列表失败,请稍后重试')
products.value = []
2026-02-24 09:59:22 +08:00
} finally {
loading.value = false
}
2026-02-26 11:16:24 +08:00
}
const syncRouteFilters = async () => {
const keyword = typeof route.query.keyword === 'string' ? route.query.keyword.trim() : ''
const tag = typeof route.query.tag === 'string' ? route.query.tag.trim() : ''
2026-02-26 11:16:24 +08:00
searchKeyword.value = keyword
showSearch.value = Boolean(keyword)
selectedCategory.value = tag && categories.value.includes(tag) ? tag : '全部'
await fetchProducts()
}
2026-02-24 09:59:22 +08:00
const handleBackClick = () => {
router.push('/home')
}
const handleCategoryClick = (category: string) => {
selectedCategory.value = category
2026-03-05 16:02:34 +08:00
searchKeyword.value = ''
showSearch.value = false
router.replace({
path: '/products',
query: category === '全部' ? {} : { tag: category }
})
}
const handleProductClick = (item: ProductVO) => {
router.push(`/product/${item.id}`)
}
const handleAddToCart = async (item: ProductVO) => {
if (!ensureLoginForAction('加入购物车')) {
return
}
try {
await cartApi.addToCart({ productId: item.id, quantity: 1 })
2026-03-19 20:51:07 +08:00
await updateCartCount()
message.success(`已将 ${item.title || item.name || '作品'} 加入购物车`)
} catch (error) {
console.error('加入购物车失败:', error)
message.error('加入购物车失败,请稍后重试')
}
}
const handleSearch = () => {
const keyword = searchKeyword.value.trim()
router.replace({
path: '/products',
query: keyword ? { keyword } : {}
})
}
2026-02-24 09:59:22 +08:00
2026-03-05 16:02:34 +08:00
const toggleSearch = () => {
showSearch.value = !showSearch.value
if (!showSearch.value) {
searchKeyword.value = ''
router.replace({ path: '/products', query: selectedCategory.value === '全部' ? {} : { tag: selectedCategory.value } })
2026-03-05 16:02:34 +08:00
}
}
const resetFilters = () => {
selectedCategory.value = '全部'
searchKeyword.value = ''
showSearch.value = false
router.replace('/products')
2026-03-05 16:02:34 +08:00
}
watch(
() => route.query,
async () => {
await syncRouteFilters()
},
{ deep: true }
)
2026-02-24 11:34:25 +08:00
onMounted(async () => {
await fetchTags()
await syncRouteFilters()
2026-02-24 09:59:22 +08:00
})
</script>
<style scoped>
.mobile-container {
padding-top: 60px;
min-height: 100vh;
background: #f5f5f5;
}
.header {
position: fixed;
top: 0;
left: 0;
right: 0;
z-index: 100;
display: flex;
justify-content: space-between;
align-items: center;
padding: 10px 15px;
border-bottom: 1px solid #f0f0f0;
background: white;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}
.header h1 {
margin: 0;
font-size: 18px;
font-weight: 700;
}
.back-btn,
.search-btn {
width: 40px;
height: 40px;
display: flex;
align-items: center;
justify-content: center;
}
2026-03-05 16:02:34 +08:00
.search-input-container {
flex: 1;
margin: 0 10px;
}
.main-content {
display: flex;
min-height: calc(100vh - 60px);
}
.category-sidebar {
width: 92px;
background: #fafafa;
border-right: 1px solid #ececec;
overflow-y: auto;
}
.category-item {
padding: 16px 12px;
font-size: 13px;
color: #666;
text-align: center;
cursor: pointer;
transition: all 0.2s ease;
border-left: 3px solid transparent;
}
.category-item.active {
color: #1677ff;
background: white;
border-left-color: #1677ff;
font-weight: 700;
}
.product-section {
flex: 1;
padding: 16px;
overflow-y: auto;
}
.page-banner {
margin-bottom: 16px;
border-radius: 14px;
}
.product-grid {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 14px;
}
.product-card {
border-radius: 18px;
}
.product-img {
width: 100%;
aspect-ratio: 1;
2026-02-24 09:59:22 +08:00
overflow: hidden;
border-radius: 14px;
background: #eef3ff;
2026-02-24 09:59:22 +08:00
}
.product-image {
width: 100%;
height: 100%;
object-fit: cover;
}
.product-img-placeholder {
width: 100%;
height: 100%;
display: flex;
align-items: center;
justify-content: center;
font-size: 40px;
font-weight: 700;
color: rgba(0, 0, 0, 0.18);
}
.name {
margin: 12px 0 6px;
font-size: 14px;
font-weight: 700;
color: #1f1f1f;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
2026-02-24 09:59:22 +08:00
.product-meta {
display: flex;
justify-content: space-between;
gap: 8px;
font-size: 12px;
color: #8b8b9a;
2026-02-24 09:59:22 +08:00
}
.duration {
display: inline-flex;
align-items: center;
2026-02-24 09:59:22 +08:00
padding: 2px 8px;
border-radius: 999px;
background: #f4f6fb;
2026-02-24 09:59:22 +08:00
}
.stats {
display: flex;
gap: 8px;
}
.product-tags {
margin: 10px 0;
min-height: 26px;
2026-02-24 09:59:22 +08:00
}
.price-row {
display: flex;
justify-content: space-between;
align-items: center;
}
.price {
margin: 0;
font-size: 18px;
font-weight: 700;
color: #ff4d4f;
}
.empty-state,
.loading-state {
padding: 56px 0;
2026-02-24 09:59:22 +08:00
}
2026-03-24 09:50:55 +08:00
@media (min-width: 992px) {
.main-content {
max-width: var(--frontend-content-max-width);
margin: 0 auto;
width: 100%;
}
.category-sidebar {
width: 128px;
border-radius: 20px 0 0 20px;
}
.product-section {
padding: 24px;
}
.product-grid {
grid-template-columns: repeat(4, minmax(0, 1fr));
2026-03-24 09:50:55 +08:00
}
}
2026-03-19 20:51:07 +08:00
</style>