用vue设计一个购物车的逻辑代码
<template>
<div>
<h2>购物车</h2>
<ul v-for="(item, index) in cartList" :key="index">
<li class="cart-item">{{ item.name }} - {{ item.price }}元</li> <!-- 商品名称和价格 -->
<button @click="addToCart(index)">+</button><!-- 添加按钮 -->
<span class="num">{{ item.num }}</span><!-- 点击按钮后显示的数量 -->
<button @click="reduceFromCart(index)">-</button><!-- 减少按钮 -->
</ul>
<!-- 购物车总价格 -->
总价:{{ totalPrice }}元
</div> </template>
<script>
export default {
data () { // 初始化数据,用于存储购物车中的商品信息。
return {
cartList: [ // 购物车列表
{ name: 'iPhone', price: 6188, num: 1 }, // 购买一个iPhone,单价6188元,初始数量为1
{ name: 'iPad Pro', price: 5888, num: 2 } // 购买两个iPad Pro,单价5888元,初始数量为2 ], totalPrice: 0 } }, computed:{ // 计算总价格 totalPrice(){ let sum = 0; this.cartList.forEach(item =>{ sum += item.price * item.num; }); return sum; } }, methods:{ addToCart (index){ this.$set(this.cartList[index], 'num', this.cartList[index].num + 1); }, reduceFromCart (index){ if (this.cartList[index].num > 0){ this.$set(this.cartList[index], 'num', this.cartList[index].num - 1); }else{ alert('已经是最少了'); } } }; </script>
创作工场
免责声明:
以上内容除特别注明外均来源于网友提问,创作工场回答,未经许可,严谨转载。
点击这里>>使用🔥专业版,更聪明、更完整、更原创!