vue实现购物节
Vue 实现购物节功能
商品展示组件
创建商品卡片组件展示促销商品信息,包含图片、名称、原价、折扣价和倒计时。
<template>
<div class="product-card">
<img :src="product.image" :alt="product.name">
<h3>{{ product.name }}</h3>
<p class="original-price">¥{{ product.price }}</p>
<p class="discount-price">¥{{ product.discountPrice }}</p>
<div class="countdown">
剩余时间: {{ countdown.days }}天 {{ countdown.hours }}:{{ countdown.minutes }}:{{ countdown.seconds }}
</div>
<button @click="addToCart">加入购物车</button>
</div>
</template>
倒计时功能
使用计算属性和定时器实现活动倒计时功能。
data() {
return {
endTime: new Date('2023-11-11 23:59:59').getTime(),
now: Date.now(),
timer: null
}
},
computed: {
countdown() {
const diff = this.endTime - this.now
const days = Math.floor(diff / (1000 * 60 * 60 * 24))
const hours = Math.floor((diff % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60))
const minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60))
const seconds = Math.floor((diff % (1000 * 60)) / 1000)
return { days, hours, minutes, seconds }
}
},
mounted() {
this.timer = setInterval(() => {
this.now = Date.now()
}, 1000)
},
beforeDestroy() {
clearInterval(this.timer)
}
购物车功能
使用Vuex管理购物车状态,实现添加商品和计算总价功能。

// store.js
const store = new Vuex.Store({
state: {
cart: []
},
mutations: {
ADD_TO_CART(state, product) {
const existingItem = state.cart.find(item => item.id === product.id)
if (existingItem) {
existingItem.quantity++
} else {
state.cart.push({ ...product, quantity: 1 })
}
}
},
getters: {
cartTotal(state) {
return state.cart.reduce((total, item) => {
return total + (item.discountPrice * item.quantity)
}, 0)
}
}
})
优惠券功能
实现优惠券选择和使用逻辑。
<template>
<div class="coupon-selector">
<select v-model="selectedCoupon">
<option v-for="coupon in coupons" :value="coupon" :key="coupon.id">
{{ coupon.name }} (减¥{{ coupon.value }})
</option>
</select>
<p>优惠后总价: ¥{{ discountedTotal }}</p>
</div>
</template>
<script>
export default {
computed: {
discountedTotal() {
return this.$store.getters.cartTotal - (this.selectedCoupon ? this.selectedCoupon.value : 0)
}
}
}
</script>
页面布局
使用Vue Router创建活动页面和商品详情页。

const routes = [
{
path: '/promotion',
component: PromotionPage,
children: [
{
path: 'product/:id',
component: ProductDetail
}
]
}
]
响应式设计
使用CSS媒体查询确保在不同设备上良好显示。
@media (max-width: 768px) {
.product-card {
width: 100%;
margin-bottom: 20px;
}
}
性能优化
使用Vue的异步组件和懒加载提升页面加载速度。
const ProductDetail = () => import('./components/ProductDetail.vue')






