hbuilderx购物车vue
时间: 2025-05-22 17:47:46 浏览: 22
### 实现 HBuilderX 中 Vue 的购物车功能
在 HBuilderX 中使用 Vue 开发购物车功能,可以通过组件化的方式实现商品列表展示、加入购物车以及购物车结算等功能。以下是完整的示例代码:
#### 商品列表组件 (`ProductList.vue`)
此组件用于显示商品列表并提供“加入购物车”的按钮。
```html
<template>
<div class="product-list">
<h3>商品列表</h3>
<ul>
<li v-for="(item, index) in products" :key="index">
{{ item.name }} - ¥{{ item.price }}
<button @click="addToCart(item)">加入购物车</button>
</li>
</ul>
</div>
</template>
<script>
export default {
name: "ProductList",
props: ["products"],
methods: {
addToCart(product) {
this.$bus.$emit("add-to-cart", product);
}
},
};
</script>
```
---
#### 购物车组件 (`ShoppingCart.vue`)
此组件负责接收来自 `ProductList` 的数据,并计算总价。
```html
<template>
<div class="shopping-cart">
<h3>购物车</h3>
<p v-if="cartItems.length === 0">暂无商品</p>
<ul v-else>
<li v-for="(item, index) in cartItems" :key="index">
{{ item.name }} - 数量: {{ item.quantity }} - 小计: ¥{{ item.subtotal }}
</li>
</ul>
<p>总计: ¥{{ total }}</p>
</div>
</template>
<script>
export default {
name: "ShoppingCart",
data() {
return {
cartItems: [],
};
},
computed: {
total() {
return this.cartItems.reduce((sum, item) => sum + item.subtotal, 0);
},
},
mounted() {
this.$bus.$on("add-to-cart", (product) => {
const existingItem = this.cartItems.find(
(item) => item.id === product.id
);
if (existingItem) {
existingItem.quantity += 1;
existingItem.subtotal =
parseFloat(existingItem.price) * existingItem.quantity;
} else {
this.cartItems.push({
...product,
quantity: 1,
subtotal: parseFloat(product.price),
});
}
});
},
};
</script>
```
---
#### 主应用入口文件 (`App.vue`)
通过 `$bus` 来集中管理事件通信[^1]。
```html
<template>
<div id="app">
<ProductList :products="products"></ProductList>
<ShoppingCart></ShoppingCart>
</div>
</template>
<script>
import ProductList from "./components/ProductList.vue";
import ShoppingCart from "./components/ShoppingCart.vue";
let bus = new Vue();
export default {
components: { ProductList, ShoppingCart },
provide() {
return {
$bus: bus,
};
},
data() {
return {
products: [
{ id: 1, name: "苹果", price: "5.99" },
{ id: 2, name: "香蕉", price: "3.49" },
{ id: 3, name: "橙子", price: "4.79" },
],
};
},
};
</script>
```
---
#### 初始化 Vue 应用 (`main.js`)
创建 Vue 实例并将根节点挂载到 DOM 上[^2]。
```javascript
import Vue from "vue";
import App from "./App.vue";
new Vue({
render: (h) => h(App),
}).$mount("#app");
```
---
### 功能说明
1. **商品列表**:展示了可供购买的商品及其价格。
2. **购物车逻辑**:当点击“加入购物车”按钮时,会向购物车发送消息更新状态。
3. **事件总线**:利用 Vue 创建的全局事件总线来传递数据,从而实现跨组件通信。
---
阅读全文