Vue2 购物车代码示例 - 简单易懂
<template>
<div>
<h2>购物车</h2>
<ul>
<li v-for='(item, index) in cartItems' :key='index'>
{{ item.name }} - {{ item.price }}元 x {{ item.quantity }}
<button @click='removeItem(index)'>删除</button>
</li>
</ul>
<p v-if='cartItems.length === 0'>购物车为空</p>
<p v-else>共 {{totalQuantity}} 件商品,总价 {{totalPrice}} 元</p>
</div>
</template>
<script>
export default {
data() {
return {
cartItems: [
{ name: '商品1', price: 10, quantity: 2 },
{ name: '商品2', price: 20, quantity: 1 },
],
};
},
computed: {
totalPrice() {
return this.cartItems.reduce(
(total, item) => total + item.price * item.quantity,
0
);
},
totalQuantity() {
return this.cartItems.reduce((total, item) => total + item.quantity, 0);
},
},
methods: {
removeItem(index) {
this.cartItems.splice(index, 1);
},
},
};
</script>
原文地址: https://www.cveoy.top/t/topic/m8DJ 著作权归作者所有。请勿转载和采集!