面试题答案
一键面试思路
- 在
Cart.svelte
中,定义一个数组来存储购物车中的商品信息,包括商品价格、数量等。 - 将商品价格等信息通过
props
传递给ProductItem.svelte
子组件。 - 在
ProductItem.svelte
中,通过增加或减少数量的按钮触发事件,将数量变化通知给Cart.svelte
父组件。 Cart.svelte
父组件接收到数量变化事件后,重新计算总价。
关键代码片段
Cart.svelte
<script>
import ProductItem from './ProductItem.svelte';
let products = [
{ id: 1, name: 'Product 1', price: 10 },
{ id: 2, name: 'Product 2', price: 20 }
];
let totalPrice = 0;
const updateTotalPrice = () => {
totalPrice = products.reduce((acc, product) => acc + product.price * product.quantity, 0);
};
const handleQuantityChange = (productId, newQuantity) => {
products = products.map(product => {
if (product.id === productId) {
product.quantity = newQuantity;
}
return product;
});
updateTotalPrice();
};
</script>
{#each products as product}
<ProductItem
{product}
on:quantityChange={handleQuantityChange.bind(this, product.id)}
/>
{/each}
<p>Total Price: {totalPrice}</p>
ProductItem.svelte
<script>
import { createEventDispatcher } from'svelte';
const dispatcher = createEventDispatcher();
export let product;
let quantity = product.quantity || 1;
const incrementQuantity = () => {
quantity++;
dispatcher('quantityChange', quantity);
};
const decrementQuantity = () => {
if (quantity > 1) {
quantity--;
dispatcher('quantityChange', quantity);
}
};
</script>
<button on:click={decrementQuantity}>-</button>
<span>{quantity}</span>
<button on:click={incrementQuantity}>+</button>
在上述代码中:
Cart.svelte
定义了商品数组products
,并通过props
将每个商品对象传递给ProductItem.svelte
。同时,它定义了updateTotalPrice
方法用于重新计算总价,handleQuantityChange
方法用于接收子组件传来的数量变化并更新商品数量和总价。ProductItem.svelte
通过props
接收商品信息,有两个按钮分别用于增加和减少数量,在数量变化时通过createEventDispatcher
触发quantityChange
事件,并将新的数量传递出去。