vue实现淘宝商品展示
实现淘宝商品展示的Vue方案
商品列表布局
使用Vue的v-for指令渲染商品列表,配合CSS Grid或Flex布局实现响应式网格。商品卡片应包含图片、标题、价格和销量等核心信息。
<template>
<div class="product-list">
<div v-for="product in products" :key="product.id" class="product-card">
<img :src="product.image" :alt="product.title">
<h3>{{ product.title }}</h3>
<div class="price">¥{{ product.price }}</div>
<div class="sales">销量: {{ product.sales }}</div>
</div>
</div>
</template>
<style>
.product-list {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
gap: 20px;
}
.product-card {
border: 1px solid #eee;
padding: 10px;
border-radius: 4px;
}
</style>
数据获取与处理
通过axios获取后端API数据,使用计算属性处理价格显示格式。建议添加加载状态和错误处理机制。
import axios from 'axios';
export default {
data() {
return {
products: [],
loading: false,
error: null
}
},
created() {
this.fetchProducts();
},
methods: {
async fetchProducts() {
this.loading = true;
try {
const response = await axios.get('/api/products');
this.products = response.data;
} catch (err) {
this.error = err.message;
} finally {
this.loading = false;
}
}
},
computed: {
formattedProducts() {
return this.products.map(product => ({
...product,
price: product.price.toFixed(2)
}));
}
}
}
图片懒加载优化
使用Intersection Observer API或第三方库实现图片懒加载,提升页面性能。
<img v-lazy="product.image" :alt="product.title">
// 注册自定义指令
Vue.directive('lazy', {
inserted: (el, binding) => {
const observer = new IntersectionObserver((entries) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
el.src = binding.value;
observer.unobserve(el);
}
});
});
observer.observe(el);
}
});
商品筛选与排序
实现价格区间筛选、销量排序等功能,使用计算属性避免直接修改原始数据。
computed: {
filteredProducts() {
return this.products
.filter(product => product.price >= this.minPrice && product.price <= this.maxPrice)
.sort((a, b) => {
if (this.sortBy === 'price') {
return a.price - b.price;
} else if (this.sortBy === 'sales') {
return b.sales - a.sales;
}
return 0;
});
}
}
分页加载
实现无限滚动或传统分页,控制数据加载量。
methods: {
loadMore() {
if (this.page < this.totalPages) {
this.page++;
this.fetchProducts();
}
}
},
created() {
window.addEventListener('scroll', () => {
if ((window.innerHeight + window.scrollY) >= document.body.offsetHeight - 500) {
this.loadMore();
}
});
}
商品详情交互
使用Vue Router实现商品详情页跳转,通过路由参数传递商品ID。
// router.js
{
path: '/product/:id',
component: ProductDetail
}
// 列表页跳转
<router-link :to="'/product/' + product.id">查看详情</router-link>
响应式设计要点
确保在不同设备上正常显示,使用媒体查询调整布局。
@media (max-width: 768px) {
.product-list {
grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
gap: 10px;
}
}






