当前位置:首页 > VUE

用vue实现简易购物车

2026-01-07 06:46:53VUE

实现步骤

创建一个Vue项目,确保已安装Vue CLI。可以通过以下命令初始化项目:

vue create shopping-cart
cd shopping-cart
npm run serve

项目结构

src目录下创建以下文件:

  • components/CartItem.vue:单个商品组件
  • components/CartList.vue:购物车列表组件
  • App.vue:主入口文件

数据准备

App.vue中定义商品数据和购物车状态:

用vue实现简易购物车

data() {
  return {
    products: [
      { id: 1, name: '商品A', price: 100, stock: 5 },
      { id: 2, name: '商品B', price: 200, stock: 3 },
      { id: 3, name: '商品C', price: 300, stock: 2 }
    ],
    cart: []
  }
}

商品列表组件

创建CartList.vue组件用于展示商品列表和添加功能:

<template>
  <div>
    <h3>商品列表</h3>
    <ul>
      <li v-for="product in products" :key="product.id">
        {{ product.name }} - ¥{{ product.price }}
        <button @click="addToCart(product)">加入购物车</button>
      </li>
    </ul>
  </div>
</template>

<script>
export default {
  props: ['products'],
  methods: {
    addToCart(product) {
      this.$emit('add-to-cart', product)
    }
  }
}
</script>

购物车组件

创建CartItem.vue组件显示购物车内容:

用vue实现简易购物车

<template>
  <div>
    <h3>购物车</h3>
    <div v-if="cart.length === 0">购物车为空</div>
    <ul v-else>
      <li v-for="(item, index) in cart" :key="index">
        {{ item.name }} × {{ item.quantity }} - ¥{{ item.price * item.quantity }}
        <button @click="removeItem(index)">删除</button>
      </li>
    </ul>
    <div v-if="cart.length > 0">
      总价: ¥{{ totalPrice }}
    </div>
  </div>
</template>

<script>
export default {
  props: ['cart'],
  computed: {
    totalPrice() {
      return this.cart.reduce((sum, item) => sum + item.price * item.quantity, 0)
    }
  },
  methods: {
    removeItem(index) {
      this.$emit('remove-item', index)
    }
  }
}
</script>

主组件整合

App.vue中整合功能:

<template>
  <div>
    <CartList :products="products" @add-to-cart="handleAddToCart" />
    <CartItem :cart="cart" @remove-item="handleRemoveItem" />
  </div>
</template>

<script>
import CartList from './components/CartList.vue'
import CartItem from './components/CartItem.vue'

export default {
  components: { CartList, CartItem },
  methods: {
    handleAddToCart(product) {
      const existingItem = this.cart.find(item => item.id === product.id)
      if (existingItem) {
        existingItem.quantity++
      } else {
        this.cart.push({ ...product, quantity: 1 })
      }
    },
    handleRemoveItem(index) {
      this.cart.splice(index, 1)
    }
  }
}
</script>

样式优化

添加基础样式增强用户体验:

ul {
  list-style: none;
  padding: 0;
}
li {
  margin: 10px 0;
  padding: 10px;
  border: 1px solid #eee;
}
button {
  margin-left: 10px;
  cursor: pointer;
}

功能扩展建议

  • 添加本地存储持久化购物车数据
  • 实现商品数量增减按钮
  • 添加结算功能
  • 实现商品库存实时更新

以上实现提供了购物车核心功能,包括商品展示、添加至购物车、删除商品和计算总价。可以根据实际需求进一步扩展功能。

标签: 购物车简易
分享给朋友: