MST
星途 面试题库

面试题:Svelte动态组件中Props与事件协同处理复杂交互场景

设想一个电商购物车场景,有一个`Cart.svelte`父组件动态加载`ProductItem.svelte`子组件。`ProductItem`可以增加或减少数量,同时`Cart`需要实时更新总价。请详细描述如何通过Props传递商品价格等信息,以及如何通过事件实现数量变化通知父组件更新总价,给出关键代码片段及思路。
41.7万 热度难度
前端开发Svelte

知识考点

AI 面试

面试题答案

一键面试

思路

  1. Cart.svelte 中,定义一个数组来存储购物车中的商品信息,包括商品价格、数量等。
  2. 将商品价格等信息通过 props 传递给 ProductItem.svelte 子组件。
  3. ProductItem.svelte 中,通过增加或减少数量的按钮触发事件,将数量变化通知给 Cart.svelte 父组件。
  4. 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>

在上述代码中:

  1. Cart.svelte 定义了商品数组 products,并通过 props 将每个商品对象传递给 ProductItem.svelte。同时,它定义了 updateTotalPrice 方法用于重新计算总价,handleQuantityChange 方法用于接收子组件传来的数量变化并更新商品数量和总价。
  2. ProductItem.svelte 通过 props 接收商品信息,有两个按钮分别用于增加和减少数量,在数量变化时通过 createEventDispatcher 触发 quantityChange 事件,并将新的数量传递出去。