标签功能初版实现

This commit is contained in:
xiaowang
2026-02-24 09:59:22 +08:00
parent c5018b14a5
commit aa0aca2ac0
56 changed files with 2273 additions and 305 deletions
+1 -8
View File
@@ -20,15 +20,8 @@ import BottomNav from './components/BottomNav.vue'
const route = useRoute()
// 计算是否需要隐藏导航栏
const isHiddenNav = computed(() => {
// 需要隐藏导航栏的页面路径
const hiddenNavRoutes = ['/settings']
// 检查是否是商品详情页(/product/数字)
const isProductDetail = /^\/product\/\d+$/.test(route.path)
return hiddenNavRoutes.some(path => route.path.startsWith(path)) || isProductDetail
return route.meta.hideNav as boolean
})
</script>
+59
View File
@@ -0,0 +1,59 @@
import api from './index'
export interface LoginRequest {
account: string
password: string
rememberMe?: boolean
}
export interface RegisterRequest {
account: string
password: string
nickname: string
shopId?: number
}
export interface LoginResponse {
accessToken: string
refreshToken: string
userInfo: UserInfo
}
export interface UserInfo {
id: number
account: string
nickname: string
avatar?: string
createTime: string
}
export interface RefreshTokenRequest {
refreshToken: string
}
export interface RefreshTokenResponse {
accessToken: string
refreshToken: string
}
export const authApi = {
login: (data: LoginRequest) => {
return api.post<LoginResponse>('/user/login', data)
},
register: (data: RegisterRequest) => {
return api.post('/user/register', data)
},
refreshToken: (data: RefreshTokenRequest) => {
return api.post<RefreshTokenResponse>('/user/refresh-token', data)
},
logout: () => {
return api.post('/user/logout')
},
getUserInfo: () => {
return api.get<UserInfo>('/user/info')
}
}
+105
View File
@@ -0,0 +1,105 @@
import axios, { AxiosError } from 'axios'
import { authApi } from './auth'
import router from '../router'
const api = axios.create({
baseURL: 'http://localhost:8088/api',
timeout: 10000,
headers: {
'Content-Type': 'application/json'
}
})
let isRefreshing = false
let failedQueue: Array<{
resolve: (value?: any) => void
reject: (reason?: any) => void
}> = []
const processQueue = (error: any, token: string | null = null) => {
failedQueue.forEach(prom => {
if (error) {
prom.reject(error)
} else {
prom.resolve(token)
}
})
failedQueue = []
}
api.interceptors.request.use(
config => {
let token = localStorage.getItem('accessToken')
if (!token) {
token = sessionStorage.getItem('accessToken')
}
if (token) {
config.headers.Authorization = `Bearer ${token}`
}
return config
},
error => {
return Promise.reject(error)
}
)
api.interceptors.response.use(
response => {
return response.data.data
},
async (error: AxiosError) => {
const originalRequest = error.config as any
if (error.response?.status === 401 && !originalRequest._retry) {
if (isRefreshing) {
return new Promise((resolve, reject) => {
failedQueue.push({ resolve, reject })
}).then(token => {
if (token) {
originalRequest.headers.Authorization = `Bearer ${token}`
}
return api(originalRequest)
}).catch(err => {
return Promise.reject(err)
})
}
originalRequest._retry = true
isRefreshing = true
try {
const refreshToken = localStorage.getItem('refreshToken')
if (!refreshToken) {
throw new Error('No refresh token available')
}
const response = await authApi.refreshToken({ refreshToken })
const newToken = response.data.accessToken
const newRefreshToken = response.data.refreshToken
localStorage.setItem('accessToken', newToken)
localStorage.setItem('refreshToken', newRefreshToken)
sessionStorage.setItem('accessToken', newToken)
processQueue(null, newToken)
originalRequest.headers.Authorization = `Bearer ${newToken}`
return api(originalRequest)
} catch (refreshError) {
processQueue(refreshError, null)
localStorage.removeItem('accessToken')
localStorage.removeItem('refreshToken')
sessionStorage.removeItem('accessToken')
router.push('/auth')
return Promise.reject(refreshError)
} finally {
isRefreshing = false
}
}
console.error('API Error:', error)
return Promise.reject(error)
}
)
export default api
+59
View File
@@ -0,0 +1,59 @@
import api from './index'
export interface ProductVO {
id: number
shopId: number
shopName: string
title: string
description: string
imageFileIds: string
imageUrls: string[]
price: number
tags: string
tagList: string[]
likeCount: number
collectCount: number
approximateDuration: string
bookableArtists: string
availableCoupons: string
createTime: string
updateTime: string
}
export interface ProductDTO {
shopId: number
title: string
description: string
imageFileIds: string
price: number
tags: string
approximateDuration: string
bookableArtists: string
availableCoupons: string
}
export const productApi = {
getAllProducts: () => {
return api.get<ProductVO[]>('/product/list/all')
},
getProductById: (id: number) => {
return api.get<ProductVO>(`/product/get/${id}`)
},
getProductsByTag: (tag: string) => {
return api.get<ProductVO[]>(`/product/list/tag/${tag}`)
},
createProduct: (data: ProductDTO) => {
return api.post<ProductVO>('/product/add', data)
},
updateProduct: (id: number, data: ProductDTO) => {
return api.put<ProductVO>(`/product/update/${id}`, data)
},
deleteProduct: (id: number) => {
return api.delete(`/product/delete/${id}`)
}
}
+31
View File
@@ -0,0 +1,31 @@
import api from './index'
export interface ShopVO {
id: number
shopName: string
address: string
phone: string
businessHours: string
description: string
createTime: string
updateTime: string
}
export interface ShopSimpleVO {
id: number
shopName: string
}
export const shopApi = {
getAllShops: () => {
return api.get<ShopVO[]>('/shop/list/all')
},
getShopsSimple: () => {
return api.get<ShopSimpleVO[]>('/shop/list/simple')
},
getShopById: (id: number) => {
return api.get<ShopVO>(`/shop/get/${id}`)
}
}
+40
View File
@@ -0,0 +1,40 @@
import api from './index'
export interface TagVO {
id: number
tagName: string
textColor: string
bgColor: string
borderColor: string
createTime: string
updateTime: string
}
export interface TagDTO {
tagName: string
textColor: string
bgColor: string
borderColor: string
}
export const tagApi = {
getAllTags: () => {
return api.get<TagVO[]>('/tag/list/all')
},
getTagById: (id: number) => {
return api.get<TagVO>(`/tag/get/${id}`)
},
createTag: (data: TagDTO) => {
return api.post<TagVO>('/tag/add', data)
},
updateTag: (id: number, data: TagDTO) => {
return api.put<TagVO>(`/tag/update/${id}`, data)
},
deleteTag: (id: number) => {
return api.delete(`/tag/delete/${id}`)
}
}
+1 -4
View File
@@ -12,13 +12,10 @@ export {}
declare module 'vue' {
export interface GlobalComponents {
BottomNav: typeof import('./components/BottomNav.vue')['default']
ElAvatar: typeof import('element-plus/es')['ElAvatar']
ElBadge: typeof import('element-plus/es')['ElBadge']
ElButton: typeof import('element-plus/es')['ElButton']
ElConfigProvider: typeof import('element-plus/es')['ElConfigProvider']
ElIcon: typeof import('element-plus/es')['ElIcon']
ElInput: typeof import('element-plus/es')['ElInput']
ElRate: typeof import('element-plus/es')['ElRate']
ElTag: typeof import('element-plus/es')['ElTag']
HelloWorld: typeof import('./components/HelloWorld.vue')['default']
RouterLink: typeof import('vue-router')['RouterLink']
RouterView: typeof import('vue-router')['RouterView']
+33 -7
View File
@@ -6,39 +6,65 @@ const router = createRouter({
{
path: '/',
name: 'home',
component: () => import('../views/HomeView.vue')
component: () => import('../views/HomeView.vue'),
meta: { requiresAuth: false }
},
{
path: '/auth',
name: 'auth',
component: () => import('../views/AuthView.vue'),
meta: { requiresAuth: false, hideNav: true }
},
{
path: '/products',
name: 'products',
component: () => import('../views/ProductListView.vue')
component: () => import('../views/ProductListView.vue'),
meta: { requiresAuth: true }
},
{
path: '/product/:id',
name: 'product-detail',
component: () => import('../views/ProductDetailView.vue')
component: () => import('../views/ProductDetailView.vue'),
meta: { requiresAuth: true, hideNav: true }
},
{
path: '/cart',
name: 'cart',
component: () => import('../views/CartView.vue')
component: () => import('../views/CartView.vue'),
meta: { requiresAuth: true }
},
{
path: '/profile',
name: 'profile',
component: () => import('../views/ProfileView.vue')
component: () => import('../views/ProfileView.vue'),
meta: { requiresAuth: true }
},
{
path: '/wishlist',
name: 'wishlist',
component: () => import('../views/WishlistView.vue')
component: () => import('../views/WishlistView.vue'),
meta: { requiresAuth: true }
},
{
path: '/settings',
name: 'settings',
component: () => import('../views/SettingsView.vue')
component: () => import('../views/SettingsView.vue'),
meta: { requiresAuth: true, hideNav: true }
}
]
})
router.beforeEach((to, _from, next) => {
const token = localStorage.getItem('accessToken')
const requiresAuth = to.meta.requiresAuth as boolean
if (requiresAuth && !token) {
next('/auth')
} else if (to.path === '/auth' && token) {
next('/')
} else {
next()
}
})
export default router
+396
View File
@@ -0,0 +1,396 @@
<template>
<div class="mobile-container">
<div class="auth-container">
<div class="logo-section">
<div class="logo">Yumi</div>
<div class="subtitle">美甲服务平台</div>
</div>
<div class="tab-container">
<div
class="tab-item"
:class="{ active: activeTab === 'login' }"
@click="activeTab = 'login'"
>
登录
</div>
<div
class="tab-item"
:class="{ active: activeTab === 'register' }"
@click="activeTab = 'register'"
>
注册
</div>
</div>
<a-form
:model="formData"
:rules="rules"
@finish="handleSubmit"
layout="vertical"
class="auth-form"
>
<a-form-item name="account" label="账号">
<a-input
v-model:value="formData.account"
placeholder="请输入账号"
size="large"
>
<template #prefix>
<UserOutlined style="color: #999" />
</template>
</a-input>
</a-form-item>
<a-form-item name="password" label="密码">
<a-input-password
v-model:value="formData.password"
placeholder="请输入密码"
size="large"
>
<template #prefix>
<LockOutlined style="color: #999" />
</template>
</a-input-password>
</a-form-item>
<a-form-item v-if="activeTab === 'register'" name="confirmPassword" label="确认密码">
<a-input-password
v-model:value="formData.confirmPassword"
placeholder="请再次输入密码"
size="large"
>
<template #prefix>
<LockOutlined style="color: #999" />
</template>
</a-input-password>
</a-form-item>
<a-form-item v-if="activeTab === 'register'" name="shopId" label="选择店铺">
<a-select
v-model:value="formData.shopId"
placeholder="请选择店铺"
size="large"
:loading="loadingShops"
>
<a-select-option
v-if="shops.length === 0"
disabled
value=""
>
暂无店铺数据
</a-select-option>
<a-select-option
v-for="shop in shops"
:key="shop.id"
:value="shop.id"
>
{{ shop.shopName }}
</a-select-option>
</a-select>
</a-form-item>
<a-form-item v-if="activeTab === 'register'" name="nickname" label="昵称">
<a-input
v-model:value="formData.nickname"
placeholder="请输入昵称"
size="large"
>
<template #prefix>
<UserOutlined style="color: #999" />
</template>
</a-input>
</a-form-item>
<a-form-item v-if="activeTab === 'login'" style="margin-bottom: 8px">
<div class="form-actions">
<a-checkbox v-model:checked="formData.rememberMe">记住我</a-checkbox>
<a class="forgot-password" @click="handleForgotPassword">忘记密码?</a>
</div>
</a-form-item>
<a-form-item>
<a-button
type="primary"
html-type="submit"
size="large"
block
:loading="loading"
>
{{ activeTab === 'login' ? '登录' : '注册' }}
</a-button>
</a-form-item>
<div class="social-login">
<div class="divider">
<span>其他登录方式</span>
</div>
<div class="social-buttons">
<a-button shape="circle" size="large" @click="handleWeChatLogin">
<WechatOutlined />
</a-button>
<a-button shape="circle" size="large" @click="handleQQLogin">
<QqOutlined />
</a-button>
</div>
</div>
</a-form>
</div>
</div>
</template>
<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { UserOutlined, LockOutlined, WechatOutlined, QqOutlined } from '@ant-design/icons-vue'
import { message } from 'ant-design-vue'
import { authApi } from '@/api/auth'
import { shopApi } from '@/api/shop'
const router = useRouter()
const activeTab = ref<'login' | 'register'>('login')
const loading = ref(false)
const loadingShops = ref(false)
const shops = ref<any[]>([])
const formData = reactive({
account: '',
password: '',
confirmPassword: '',
nickname: '',
shopId: undefined as number | undefined,
rememberMe: false
})
const validatePassword = async (_rule: any, value: string) => {
if (value.length < 6) {
return Promise.reject('密码长度不能少于6位')
}
return Promise.resolve()
}
const validateConfirmPassword = async (_rule: any, value: string) => {
if (!value) {
return Promise.reject('请确认密码')
}
if (value !== formData.password) {
return Promise.reject('两次输入的密码不一致')
}
return Promise.resolve()
}
const rules = {
account: [
{ required: true, message: '请输入账号', trigger: 'blur' },
{ min: 3, max: 50, message: '账号长度在3到50个字符', trigger: 'blur' }
],
password: [
{ required: true, message: '请输入密码', trigger: 'blur' },
{ validator: validatePassword, trigger: 'blur' }
],
confirmPassword: [
{ required: true, message: '请确认密码', trigger: 'blur' },
{ validator: validateConfirmPassword, trigger: 'blur' }
],
nickname: [
{ required: true, message: '请输入昵称', trigger: 'blur' },
{ min: 2, max: 20, message: '昵称长度在2到20个字符', trigger: 'blur' }
],
shopId: [
{ required: true, message: '请选择店铺', trigger: 'change' }
]
}
const fetchShops = async () => {
loadingShops.value = true
try {
const response = await shopApi.getShopsSimple()
shops.value = response.data || []
} catch (error) {
console.error('获取店铺列表失败:', error)
message.error('获取店铺列表失败')
} finally {
loadingShops.value = false
}
}
const handleSubmit = async () => {
loading.value = true
try {
if (activeTab.value === 'login') {
const response = await authApi.login({
account: formData.account,
password: formData.password,
rememberMe: formData.rememberMe
})
const loginData = response as any
localStorage.setItem('accessToken', loginData.accessToken)
localStorage.setItem('refreshToken', loginData.refreshToken)
localStorage.setItem('userInfo', JSON.stringify(loginData.userInfo))
sessionStorage.setItem('accessToken', loginData.accessToken)
message.success('登录成功')
router.push('/products')
} else {
await authApi.register({
account: formData.account,
password: formData.password,
nickname: formData.nickname,
shopId: formData.shopId!
})
message.success('注册成功,请登录')
activeTab.value = 'login'
}
} catch (error: any) {
message.error(error.message || (activeTab.value === 'login' ? '登录失败' : '注册失败'))
} finally {
loading.value = false
}
}
const handleForgotPassword = () => {
message.info('忘记密码功能开发中')
}
const handleWeChatLogin = () => {
message.info('微信登录功能开发中')
}
const handleQQLogin = () => {
message.info('QQ登录功能开发中')
}
onMounted(() => {
fetchShops()
})
</script>
<style scoped>
.mobile-container {
min-height: 100vh;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
display: flex;
align-items: center;
justify-content: center;
padding: 20px;
}
.auth-container {
width: 100%;
max-width: 400px;
background: white;
border-radius: 20px;
padding: 30px;
box-shadow: 0 10px 40px rgba(0, 0, 0, 0.1);
}
.logo-section {
text-align: center;
margin-bottom: 30px;
}
.logo {
font-size: 48px;
font-weight: bold;
color: #667eea;
margin-bottom: 10px;
}
.subtitle {
font-size: 16px;
color: #999;
}
.tab-container {
display: flex;
margin-bottom: 30px;
border-bottom: 2px solid #f0f0f0;
}
.tab-item {
flex: 1;
text-align: center;
padding: 15px;
font-size: 16px;
color: #999;
cursor: pointer;
transition: all 0.3s;
position: relative;
}
.tab-item.active {
color: #667eea;
font-weight: bold;
}
.tab-item.active::after {
content: '';
position: absolute;
bottom: -2px;
left: 0;
right: 0;
height: 2px;
background: #667eea;
}
.auth-form {
margin-top: 20px;
}
.form-actions {
display: flex;
justify-content: space-between;
align-items: center;
}
.forgot-password {
color: #667eea;
cursor: pointer;
}
.social-login {
margin-top: 30px;
}
.divider {
text-align: center;
position: relative;
margin-bottom: 20px;
}
.divider::before {
content: '';
position: absolute;
left: 0;
top: 50%;
width: 100%;
height: 1px;
background: #f0f0f0;
}
.divider span {
background: white;
padding: 0 15px;
color: #999;
font-size: 14px;
position: relative;
}
.social-buttons {
display: flex;
justify-content: center;
gap: 20px;
}
.social-buttons .ant-btn {
border-color: #f0f0f0;
}
.social-buttons .ant-btn:hover {
border-color: #667eea;
color: #667eea;
}
</style>
+1 -1
View File
@@ -45,7 +45,7 @@
:min="1"
:max="99"
size="small"
@change="(val) => handleQuantityChange(item, val)"
@change="(val: number | null) => handleQuantityChange(item, val)"
/>
<a-popconfirm
title="确定要删除这个商品吗?"
+208 -172
View File
@@ -6,72 +6,67 @@
<div class="back-btn" @click="handleBackClick">
<el-icon><ArrowLeft /></el-icon>
</div>
<h1>Product Detail</h1>
<h1>{{ product.title || '商品详情' }}</h1>
<div class="actions">
<el-icon @click="handleFavoriteClick"><Star /></el-icon>
<el-icon @click="handleFavoriteClick" :style="{ fontSize: '20px' }" :class="{ active: isFavorite }"><Star /></el-icon>
</div>
</header>
<!-- Product Image -->
<div class="product-image" :style="{ backgroundColor: product.bgColor }">
<span class="product-letter">{{ product.name[0] }}</span>
<div class="product-image-container">
<img
v-if="product.imageUrls && product.imageUrls.length > 0"
:src="product.imageUrls[0]"
:alt="product.title"
class="product-image"
/>
<div v-else class="product-image-placeholder">
<span class="product-letter">{{ product.title ? product.title[0] : '商' }}</span>
</div>
</div>
<!-- Product Info -->
<div class="product-info">
<div class="info-header">
<h2 class="product-name">{{ product.name }}</h2>
<div class="price-tag">${{ product.price }}</div>
<h2 class="product-name">{{ product.title }}</h2>
<div class="price-tag">¥{{ product.price }}</div>
</div>
<div class="rating">
<el-rate v-model="product.rating" disabled show-score text-color="#ff9900" />
<div class="shop-info">
<span class="shop-name">{{ product.shopName }}</span>
</div>
<div class="product-meta">
<div class="duration">
<el-icon><Clock /></el-icon>
<span>{{ product.approximateDuration }}</span>
</div>
<div class="stats">
<span class="like-count">
<el-icon><Star /></el-icon>
{{ product.likeCount }} 赞
</span>
<span class="collect-count">
<el-icon><Collection /></el-icon>
{{ product.collectCount }} 收藏
</span>
</div>
</div>
<div class="tags">
<el-tag v-for="(tag, index) in product.tagList" :key="index" size="small" effect="light" style="margin-right: 8px; margin-bottom: 8px">
{{ tag }}
</el-tag>
</div>
<p class="description">{{ product.description }}</p>
</div>
<!-- Size Selection -->
<div class="size-section">
<h3>Size</h3>
<div class="size-options">
<div v-for="size in sizes" :key="size"
class="size-option"
:class="{ active: selectedSize === size }"
@click="handleSizeClick(size)">
{{ size }}
</div>
</div>
</div>
<!-- Color Selection -->
<div class="color-section">
<h3>Color</h3>
<div class="color-options">
<div v-for="color in colors" :key="color.name"
class="color-option"
:class="{ active: selectedColor === color.name }"
:style="{ backgroundColor: color.value }"
@click="handleColorClick(color.name)">
</div>
</div>
</div>
<!-- Quantity -->
<div class="quantity-section">
<h3>Quantity</h3>
<div class="quantity-control">
<el-button @click="decreaseQuantity" :disabled="quantity <= 1">-</el-button>
<span class="quantity">{{ quantity }}</span>
<el-button @click="increaseQuantity">+</el-button>
</div>
</div>
<!-- Action Buttons -->
<div class="action-buttons">
<el-button class="add-cart-btn" @click="handleAddToCart">
Add to Cart
<el-icon><ShoppingCart /></el-icon>
添加到购物车
</el-button>
<el-button class="buy-now-btn" type="primary" @click="handleBuyNow">
Buy Now
<el-icon><Right /></el-icon>
立即购买
</el-button>
</div>
</div>
@@ -79,94 +74,103 @@
<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { ArrowLeft, Star } from '@element-plus/icons-vue'
import { ArrowLeft, Star, Clock, Collection, ShoppingCart, Right } from '@element-plus/icons-vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { productApi, type ProductVO } from '@/api/product'
const router = useRouter()
const route = useRoute()
const product = ref({
id: 1,
name: 'Watch',
price: 40,
bgColor: '#ffe4d6',
rating: 4.5,
description: 'This is a premium quality watch with excellent design and durability. Perfect for any occasion.'
const product = ref<ProductVO>({
id: 0,
shopId: 0,
shopName: '',
title: '',
description: '',
imageFileIds: '',
imageUrls: [],
price: 0,
tags: '',
tagList: [],
likeCount: 0,
collectCount: 0,
approximateDuration: '',
bookableArtists: '',
availableCoupons: '',
createTime: '',
updateTime: ''
})
const sizes = ['S', 'M', 'L', 'XL']
const colors = [
{ name: 'red', value: '#ff6b6b' },
{ name: 'blue', value: '#4ecdc4' },
{ name: 'black', value: '#2c3e50' },
{ name: 'white', value: '#ecf0f1' }
]
const isFavorite = ref(false)
const selectedSize = ref('M')
const selectedColor = ref('black')
const quantity = ref(1)
onMounted(() => {
// 从后端获取商品详情
const fetchProductDetail = async () => {
const productId = route.params.id
console.log('产品ID:', productId)
})
try {
const response = await productApi.getProductById(Number(productId))
// 处理返回的数据
const productData = response as any
product.value = {
...productData,
imageUrls: productData.imageUrls || [],
tagList: productData.tagList || []
}
} catch (error) {
console.error('获取商品详情失败:', error)
ElMessage.error('获取商品详情失败,请稍后重试')
}
}
const handleBackClick = () => {
console.log('返回按钮被点击')
router.back()
}
const handleFavoriteClick = () => console.log('收藏按钮被点击')
const handleSizeClick = (size: string) => {
console.log('选择尺码:', size)
selectedSize.value = size
}
const handleColorClick = (color: string) => {
console.log('选择颜色:', color)
selectedColor.value = color
}
const decreaseQuantity = () => {
if (quantity.value > 1) {
quantity.value--
console.log('数量减少:', quantity.value)
}
}
const increaseQuantity = () => {
quantity.value++
console.log('数量增加:', quantity.value)
const handleFavoriteClick = () => {
isFavorite.value = !isFavorite.value
console.log('收藏状态:', isFavorite.value)
ElMessage.success(isFavorite.value ? '已收藏' : '已取消收藏')
}
const handleAddToCart = () => {
console.log('添加到购物车:', {
product: product.value,
size: selectedSize.value,
color: selectedColor.value,
quantity: quantity.value
})
console.log('添加到购物车:', product.value.title)
ElMessage.success(`已将 ${product.value.title} 添加到购物车`)
}
const handleBuyNow = () => {
console.log('立即购买:', {
product: product.value,
size: selectedSize.value,
color: selectedColor.value,
quantity: quantity.value
})
console.log('立即购买:', product.value.title)
// 这里可以跳转到订单确认页面
ElMessage.success('跳转到订单确认页面')
}
// 页面挂载时获取商品详情
onMounted(() => {
fetchProductDetail()
})
</script>
<style scoped>
.mobile-container {
min-height: 100vh;
background: #f5f5f5;
}
.header {
display: flex;
justify-content: space-between;
align-items: center;
padding: 15px 20px;
border-bottom: 1px solid #f0f0f0;
background: white;
position: sticky;
top: 0;
z-index: 100;
}
.back-btn {
width: 40px;
height: 40px;
@@ -174,10 +178,13 @@ const handleBuyNow = () => {
align-items: center;
cursor: pointer;
}
.header h1 {
font-size: 18px;
font-weight: bold;
margin: 0;
}
.actions {
width: 40px;
display: flex;
@@ -186,124 +193,153 @@ const handleBuyNow = () => {
cursor: pointer;
}
.product-image {
.actions .active {
color: #ff4d4f;
}
.product-image-container {
width: 100%;
height: 300px;
background: white;
position: relative;
}
.product-image {
width: 100%;
height: 100%;
object-fit: cover;
}
.product-image-placeholder {
width: 100%;
height: 100%;
display: flex;
justify-content: center;
align-items: center;
font-size: 80px;
font-weight: bold;
color: rgba(0,0,0,0.1);
background: #f8f8f8;
}
.product-info {
padding: 20px;
background: white;
margin-bottom: 10px;
}
.info-header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 10px;
align-items: flex-start;
margin-bottom: 12px;
}
.product-name {
font-size: 24px;
font-size: 20px;
font-weight: bold;
margin: 0;
flex: 1;
margin-right: 15px;
}
.price-tag {
font-size: 24px;
color: var(--primary-color);
font-size: 22px;
color: #ff4d4f;
font-weight: bold;
white-space: nowrap;
}
.rating {
margin-bottom: 15px;
.shop-info {
margin-bottom: 12px;
}
.shop-name {
font-size: 14px;
color: #666;
background: #f8f8f8;
padding: 4px 12px;
border-radius: 12px;
}
.product-meta {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 16px;
padding: 12px;
background: #f8f8f8;
border-radius: 8px;
}
.duration {
display: flex;
align-items: center;
gap: 6px;
font-size: 14px;
color: #666;
}
.stats {
display: flex;
gap: 16px;
}
.like-count, .collect-count {
display: flex;
align-items: center;
gap: 4px;
font-size: 14px;
color: #666;
}
.tags {
margin-bottom: 16px;
display: flex;
flex-wrap: wrap;
gap: 8px;
}
.description {
color: #666;
line-height: 1.6;
}
.size-section, .color-section, .quantity-section {
padding: 20px;
border-top: 1px solid #f0f0f0;
}
.size-section h3, .color-section h3, .quantity-section h3 {
margin: 0 0 15px 0;
font-size: 16px;
font-weight: bold;
}
.size-options {
display: flex;
gap: 10px;
}
.size-option {
width: 45px;
height: 45px;
border: 2px solid #ddd;
border-radius: 10px;
display: flex;
justify-content: center;
align-items: center;
cursor: pointer;
transition: all 0.3s;
}
.size-option.active {
border-color: var(--primary-color);
background-color: var(--primary-color);
color: white;
}
.color-options {
display: flex;
gap: 15px;
}
.color-option {
width: 40px;
height: 40px;
border-radius: 50%;
cursor: pointer;
border: 3px solid transparent;
transition: all 0.3s;
}
.color-option.active {
border-color: var(--primary-color);
transform: scale(1.1);
}
.quantity-control {
display: flex;
align-items: center;
gap: 15px;
}
.quantity {
font-size: 18px;
font-weight: bold;
min-width: 30px;
text-align: center;
font-size: 14px;
margin: 0;
}
.action-buttons {
padding: 20px;
display: flex;
gap: 15px;
padding-bottom: 20px;
background: white;
margin-top: 10px;
position: sticky;
bottom: 0;
z-index: 90;
border-top: 1px solid #f0f0f0;
}
.add-cart-btn, .buy-now-btn {
flex: 1;
height: 50px;
border-radius: 25px;
font-size: 16px;
font-weight: bold;
display: flex;
align-items: center;
justify-content: center;
gap: 8px;
}
.add-cart-btn {
background-color: #f5f5f5;
border: none;
border: 1px solid #e8e8e8;
color: #333;
}
.buy-now-btn {
background-color: var(--primary-color);
background-color: #ff4d4f;
border: none;
color: white;
}
</style>
+198 -44
View File
@@ -40,47 +40,94 @@
@click="handleProductClick(item)"
>
<!-- 商品图片 -->
<div class="product-img" :style="{ backgroundColor: item.bgColor }">
<span>{{ item.name[0] }}</span>
<div class="product-img">
<img
v-if="item.imageUrls && item.imageUrls.length > 0"
:src="item.imageUrls[0]"
:alt="item.title"
class="product-image"
/>
<div v-else class="product-img-placeholder">
<span>{{ item.title ? item.title[0] : '商' }}</span>
</div>
<a-badge
v-if="item.tag"
:text="item.tag"
v-if="item.tagList && item.tagList.length > 0"
:text="item.tagList[0]"
color="#ff4d4f"
class="product-tag"
/>
</div>
<!-- 商品信息 -->
<div class="product-info">
<p class="name">{{ item.title }}</p>
<div class="product-meta">
<span class="duration">{{ item.approximateDuration }}</span>
<div class="stats">
<span class="like-count">{{ item.likeCount }} 赞</span>
<span class="collect-count">{{ item.collectCount }} 收藏</span>
</div>
</div>
<!-- 标签展示 -->
<div class="product-tags">
<template v-if="item.tags">
<a-tag
v-for="(tagIdStr, index) in item.tags.split(';')"
:key="index"
size="small"
:style="{
marginRight: '4px',
marginBottom: '4px',
fontSize: '9px',
padding: '1px 6px',
color: getTagById(Number(tagIdStr))?.textColor || '#333333',
backgroundColor: getTagById(Number(tagIdStr))?.bgColor || '#F0F0F0',
borderColor: getTagById(Number(tagIdStr))?.borderColor || '#F0F0F0',
borderWidth: '1px',
borderStyle: 'solid',
borderRadius: '8px'
}"
>
{{ getTagById(Number(tagIdStr))?.tagName || `标签${tagIdStr}` }}
</a-tag>
</template>
<a-tag v-else size="small" color="gray" style="font-size: 10px; padding: 2px 6px">
无标签
</a-tag>
</div>
<div class="price-row">
<p class="price">¥{{ item.price }}</p>
<a-button
type="primary"
size="small"
shape="circle"
@click.stop="handleAddToCart(item)"
>
<ShoppingCartOutlined />
</a-button>
</div>
</div>
</a-card>
</div>
<!-- 商品信息 -->
<div class="product-info">
<p class="name">{{ item.name }}</p>
<div class="price-row">
<p class="price">${{ item.price }}</p>
<a-button
type="primary"
size="small"
shape="circle"
@click.stop="handleAddToCart(item)"
>
<ShoppingCartOutlined />
</a-button>
</div>
</div>
</a-card>
</div>
<!-- 加载更多 -->
<div class="load-more">
<a-button v-if="hasMore" type="link" @click="handleLoadMore">
加载更多 <DownOutlined />
</a-button>
<a-typography-text v-else type="secondary">没有更多商品了</a-typography-text>
</div>
<!-- 空状态 -->
<div v-if="products.length === 0 && !loading" class="empty-state">
<a-typography-text type="secondary">商家暂未上架更多商品</a-typography-text>
</div>
<!-- 加载更多 -->
<div v-else-if="products.length > 0" class="load-more">
<a-button v-if="hasMore" type="link" @click="handleLoadMore">
加载更多 <DownOutlined />
</a-button>
<a-typography-text v-else type="secondary">没有更多商品了</a-typography-text>
</div>
</div>
</div>
</div>
</template>
<script setup lang="ts">
import { ref } from 'vue'
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import {
LeftOutlined,
@@ -89,28 +136,77 @@ import {
DownOutlined
} from '@ant-design/icons-vue'
import { message } from 'ant-design-vue'
import { productApi, type ProductVO } from '@/api/product'
import { tagApi, type TagVO } from '@/api/tag'
const router = useRouter()
// 标签列表
const allTags = ref<TagVO[]>([])
// 当前选中的分类
const selectedCategory = ref('全部')
// 分类列表
const categories = ['全部', '电子产品', '服装', '配饰', '家居']
const categories = ['全部', '美甲', '美睫', '手足护理', '纹绣']
// 商品数据
const products = ref([
{ id: 1, name: 'Watch', price: 40, bgColor: '#ffe4d6', tag: '热销' },
{ id: 2, name: 'LG TV', price: 330, bgColor: '#f0d6ff', tag: '新品' },
{ id: 3, name: 'Jacket', price: 50, bgColor: '#ffd6e2' },
{ id: 4, name: 'Nike Shoes', price: 430, bgColor: '#d6eaff', tag: '限时' },
{ id: 5, name: 'Airpods', price: 333, bgColor: '#e2ffd6' },
{ id: 6, name: 'Hoodie', price: 50, bgColor: '#d6fff0' }
])
const products = ref<ProductVO[]>([])
// 是否还有更多数据
const hasMore = ref(true)
// 加载状态
const loading = ref(false)
// 从后端获取标签列表
const fetchTags = async () => {
try {
const tags = await tagApi.getAllTags()
allTags.value = tags as unknown as TagVO[]
} catch (error) {
console.error('获取标签失败:', error)
}
}
// 根据标签ID获取标签信息
const getTagById = (tagId: number): TagVO | undefined => {
return allTags.value.find((tag: TagVO) => tag.id === tagId)
}
// 从后端获取商品数据
const fetchProducts = async () => {
if (loading.value) return
loading.value = true
try {
let response: any
if (selectedCategory.value === '全部') {
response = await productApi.getAllProducts()
} else {
response = await productApi.getProductsByTag(selectedCategory.value)
}
// 处理返回的数据
console.log('Products response:', response)
products.value = (response as ProductVO[]).map(product => ({
...product,
imageUrls: product.imageUrls || [],
tagList: product.tagList || []
}))
console.log('Processed products:', products.value)
hasMore.value = false
} catch (error) {
console.error('获取商品失败:', error)
message.error('获取商品失败,请稍后重试')
} finally {
loading.value = false
}
}
// 处理返回按钮点击
const handleBackClick = () => {
console.log('返回按钮被点击')
@@ -122,18 +218,19 @@ const handleCategoryClick = (category: string) => {
console.log('选择分类:', category)
selectedCategory.value = category
// 这里可以添加筛选逻辑
fetchProducts()
}
// 处理商品卡片点击
const handleProductClick = (item: any) => {
console.log('商品被点击:', item.name)
console.log('商品被点击:', item.title)
router.push(`/product/${item.id}`)
}
// 处理添加到购物车
const handleAddToCart = (item: any) => {
console.log('添加到购物车:', item.name)
message.success(`已将 ${item.name} 添加到购物车`)
console.log('添加到购物车:', item.title)
message.success(`已将 ${item.title} 添加到购物车`)
}
// 处理加载更多
@@ -142,6 +239,12 @@ const handleLoadMore = () => {
// 这里可以添加加载更多逻辑
hasMore.value = false
}
// 页面挂载时获取商品数据
onMounted(() => {
fetchTags()
fetchProducts()
})
</script>
<style scoped>
@@ -252,15 +355,27 @@ const handleLoadMore = () => {
width: 100%;
aspect-ratio: 1;
border-radius: 12px;
position: relative;
overflow: hidden;
margin-bottom: 10px;
background: #f8f8f8;
}
.product-image {
width: 100%;
height: 100%;
object-fit: cover;
}
.product-img-placeholder {
width: 100%;
height: 100%;
display: flex;
justify-content: center;
align-items: center;
font-size: 40px;
font-weight: bold;
color: rgba(0,0,0,0.1);
margin-bottom: 10px;
position: relative;
overflow: hidden;
}
.product-tag {
@@ -285,6 +400,32 @@ const handleLoadMore = () => {
text-overflow: ellipsis;
}
.product-meta {
font-size: 12px;
color: #999;
margin-bottom: 6px;
display: flex;
justify-content: space-between;
align-items: center;
}
.duration {
background: #f0f0f0;
padding: 2px 8px;
border-radius: 10px;
}
.stats {
display: flex;
gap: 8px;
}
.like-count,
.collect-count {
display: flex;
align-items: center;
}
.price-row {
display: flex;
justify-content: space-between;
@@ -298,8 +439,21 @@ const handleLoadMore = () => {
font-size: 16px;
}
.product-tags {
margin: 8px 0;
display: flex;
flex-wrap: wrap;
}
.load-more {
padding: 20px;
text-align: center;
}
.empty-state {
padding: 60px 20px;
text-align: center;
color: #999;
font-size: 14px;
}
</style>
+1 -1
View File
@@ -83,7 +83,7 @@
</template>
<script setup lang="ts">
import { ref, h } from 'vue'
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import {
SettingOutlined,