CSS + JS + Vue 实现购物车功能

223 阅读1分钟

模仿淘宝 App 的购物车功能,我们可以实现单选、全选、增加/减少数量以及移除商品等功能。下面是一个简单的实现示例。

Vue 组件

创建一个名为 ShoppingCart.vue 的组件:

<template>
  <div class="cart-container">
    <h3>购物车</h3>
    <div>
      <input type="checkbox" v-model="selectAll" @change="toggleSelectAll" />
      全选
    </div>
    <ul class="cart-items">
      <li v-for="(item, index) in cart" :key="index">
        <input type="checkbox" v-model="item.selected" @change="updateSelectAll" />
        {{ item.name }} - {{ item.price }}元 x {{ item.quantity }}
        <button @click="incrementQuantity(index)">+</button>
        <button @click="decrementQuantity(index)">-</button>
        <button @click="removeFromCart(index)">移除</button>
      </li>
    </ul>
    <div>总价:{{ totalPrice }}元</div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      selectAll: false,
      cart: [
        { id: 1, name: "商品1", price: 100, quantity: 1, selected: false },
        { id: 2, name: "商品2", price: 200, quantity: 1, selected: false },
        // 更多商品...
      ],
    };
  },
  computed: {
    totalPrice() {
      return this.cart.reduce(
        (total, item) => total + (item.selected ? item.price * item.quantity : 0),
        0
      );
    },
  },
  methods: {
    toggleSelectAll() {
      this.cart.forEach((item) => (item.selected = this.selectAll));
    },
    updateSelectAll() {
      this.selectAll = this.cart.every((item) => item.selected);
    },
    incrementQuantity(index) {
      this.cart[index].quantity++;
    },
    decrementQuantity(index) {
      if (this.cart[index].quantity > 1) {
        this.cart[index].quantity--;
      }
    },
    removeFromCart(index) {
      this.cart.splice(index, 1);
      this.updateSelectAll();
    },
  },
};
</script>

<style scoped>
.cart-container {
  margin: 20px;
  padding: 20px;
  border: 1px solid #ccc;
}

.cart-items {
  list-style-type: none;
  padding: 0;
}

.cart-items li {
  margin: 10px 0;
}
</style>

功能解释

  1. 数据和状态: 我们有一个 cart 数组用于存储购物车中的商品信息,以及一个 selectAll 用于表示是否全选。

  2. 全选和单选: 我们使用了 input[type="checkbox"] 元素来实现全选和单选功能。全选框的状态会影响所有商品的选中状态,而单个商品的选中状态也会影响全选框的状态。

  3. 计算总价: 我们使用了一个计算属性 totalPrice 来计算选中商品的总价。

  4. 修改商品数量: 我们定义了 incrementQuantitydecrementQuantity 方法来增加或减少商品数量。

  5. 移除商品: 我们定义了一个 removeFromCart 方法来移除商品,并在移除后更新全选状态。

  6. 样式: 我们用简单的 CSS 来添加样式。

这个组件实现了基础的购物车功能,并模仿了淘宝 App 的一些核心功能。你可以根据需要进行更多的定制和扩展。希望这个简单的示例能帮助你实现你需要的功能!