Vue 是一種先進的 JavaScript 框架,它可以為您的應用程序創建交互式用戶界面。Vue 還具有現代化的工具集,可以幫助您構建更快,更高效的 SPA 應用程序。本文將介紹如何使用 Vue 創建一個 App 購物車。
## 簡介
我們將創建一個簡單的購物車,它將包含用戶添加到其購物車中的商品,并且還將顯示購物車的總計。當用戶購買了一些商品時,我們將從購物車中刪除相應的商品。
我們將使用 Vue 的一些核心概念,包括組件,props,事件和計算屬性來創建這樣的購物車。
## 組件
組件是 Vue 應用程序中的一項核心概念。組件是一個可重復使用的代碼塊,可以根據需要在 Vue 應用程序中使用。
在我們的購物車中,我們將使用一個由兩個組件組成的體系結構:一個商品列表組件和一個購物車組件。
### 商品列表組件
商品列表組件將是我們的應用程序的入口點。它會將用戶可用的商品列表顯示出來。對于每個商品,我們將顯示名稱、價格和“添加到購物車”按鈕。
```html
{{ product.name }} - {{ product.price }}
export default {
data() {
return {
products: [
{ id: 1, name: "商品1", price: 10 },
{ id: 2, name: "商品2", price: 15 },
{ id: 3, name: "商品3", price: 20 },
],
};
},
methods: {
addToCart(product) {
this.$emit("add-to-cart", product);
},
},
};
```
### 購物車組件
購物車組件將會是我們的應用程序的核心部分。在這個組件中,我們將跟蹤用戶選擇的商品,并計算購物車的總計。
```html
{{ product.name }} - {{ product.price }} x {{ product.quantity }}
export default {
props: {
cart: { type: Array, default: () => [] },
},
computed: {
total() {
return this.cart.reduce((prev, curr) => prev + curr.price * curr.quantity, 0);
},
},
methods: {
removeFromCart(index) {
this.$emit("remove-from-cart", index);
},
},
};
```
## Props
我們的組件之間需要相互通信。商品列表組件需要將被添加到購物車的商品傳遞給購物車組件。購物車組件需要將購物車的內容傳遞回父級應用程序。
為了實現這些,我們使用 Vue 的 props 概念。props 允許我們向一個子組件傳遞數據。
我們將傳遞兩個 prop 給我們的購物車組件:cart 和 products。cart 屬性包含用戶已經選擇的商品,而 products 屬性包含所有的商品列表。
```html
import ProductList from "./ProductList.vue";
import Cart from "./Cart.vue";
export default {
components: {
ProductList,
Cart,
},
data() {
return {
cart: [],
};
},
methods: {
addToCart(product) {
const index = this.cart.findIndex((p) => p.id === product.id);
if (index < 0) {
this.cart.push({ ...product, quantity: 1 });
} else {
this.cart[index].quantity++;
}
},
removeFromCart(index) {
this.cart.splice(index, 1);
},
},
};
```
## 事件
組件之間的通信還可以通過事件實現,這是一種我們可以在子組件中發出的信號,父級組件可以偵聽此信號并采取相應的行動。
我們通過在商品列表組件中發出 add-to-cart 事件以將商品添加到購物車中,并在購物車組件中發出 remove-from-cart 事件以從購物車中刪除商品。
```html
this.$emit("add-to-cart", product);
```
```html
this.$emit("remove-from-cart", index);
```
## 計算屬性
我們的購物車需要計算其總計。為了實現這一點,我們將使用 Vue 的另一個核心概念:計算屬性。
計算屬性允許您定義一個基于其他數據的屬性,這樣每當依賴項中的數據更改時,計算屬性將被重新計算。
```html
computed: {
total() {
return this.cart.reduce((prev, curr) => prev + curr.price * curr.quantity, 0);
},
},
```
## 結論
使用 Vue 來構建應用程序始終是一件令人愉悅的事情。Vue 的清晰 API,易于使用的工具集和清晰的文檔使得開發者可以快速高效地構建出優秀的應用程序。在這篇文章中,我們學習了如何使用 Vue 來構建一個簡單的購物車,了解了組件,props,事件和計算屬性等Vue 的核心概念,這些概念在構建更大型和更困難的應用程序時將會非常有用。