MST

星途 面试题库

面试题:Svelte中writable store的复杂场景应用

假设你正在开发一个购物车功能,购物车中的商品列表数据需要使用writable store进行状态管理。要求实现以下功能:1. 能够添加商品到购物车(更新writable store);2. 计算购物车中商品的总价并实时显示(通过订阅writable store实现);3. 提供一个按钮,点击后清空购物车(重置writable store)。请给出核心代码逻辑。
31.9万 热度难度
前端开发Svelte

知识考点

AI 面试

面试题答案

一键面试

假设使用的是Svelte框架(因为提到了writable store,Svelte有此特性),以下是核心代码逻辑:

<script>
    import { writable } from'svelte/store';

    // 1. 创建writable store用于存储购物车商品列表
    const cart = writable([]);

    // 添加商品到购物车
    function addItemToCart(item) {
        cart.update(c => {
            const existingItem = c.find(i => i.id === item.id);
            if (existingItem) {
                existingItem.quantity++;
            } else {
                item.quantity = 1;
                c.push(item);
            }
            return c;
        });
    }

    // 计算购物车中商品的总价
    let totalPrice = 0;
    const unsubscribe = cart.subscribe(c => {
        totalPrice = c.reduce((acc, item) => acc + item.price * item.quantity, 0);
    });

    // 清空购物车
    function clearCart() {
        cart.set([]);
    }
</script>

{#if $cart.length > 0}
    <p>购物车总价: {totalPrice}</p>
    <button on:click={clearCart}>清空购物车</button>
{/if}

上述代码实现了:

  1. addItemToCart 函数用于添加商品到购物车,通过 cart.update 方法更新 cart 这个 writable store
  2. 使用 cart.subscribe 订阅 cart 的变化,实时计算并更新 totalPrice
  3. clearCart 函数通过 cart.set([]) 重置 cart 这个 writable store,实现清空购物车功能。