Vue.js 购物车示例:添加、删除和清空功能
<template>
<div>
<h2>购物车</h2>
<ul>
<li v-for="(item, index) in cartItems" :key="index">
'{{ item.name }}' - '{{ item.price }}'元
<button @click="removeFromCart(index)">删除</button>
</li>
</ul>
<p v-if="cartItems.length === 0">购物车是空的</p>
<div>
<button @click="clearCart">清空购物车</button>
</div>
</div>
</template>
<script>
export default {
data() {
return {
cartItems: [
{ name: '商品1', price: 10 },
{ name: '商品2', price: 20 },
{ name: '商品3', price: 30 },
],
};
},
methods: {
removeFromCart(index) {
this.cartItems.splice(index, 1);
},
clearCart() {
this.cartItems = [];
},
},
};
</script>
<style>
/* 样式 */
</style>
<p>该示例展示了如何使用 Vue.js 构建一个简单的购物车。购物车中的商品数据存储在组件的 <code>data</code> 中的 <code>cartItems</code> 数组中。使用 <code>v-for</code> 指令遍历 <code>cartItems</code> 数组,渲染购物车中的每个商品并展示其名称和价格。每个商品旁边都有一个删除按钮,点击按钮会调用 <code>removeFromCart</code> 方法,从购物车中删除对应的商品。如果购物车是空的,会展示提示信息。此外,还提供了清空购物车的按钮,点击按钮会调用 <code>clearCart</code> 方法,清空购物车中的所有商品。</p>
原文地址: https://www.cveoy.top/t/topic/lTPe 著作权归作者所有。请勿转载和采集!