MST
星途 面试题库

面试题:Svelte中如何使用衍生store组合多个基础store实现简单的逻辑计算

假设你有两个Svelte store,分别存储用户的购物车商品数量`cartQuantity`和商品单价`itemPrice`,请使用衍生store计算购物车商品的总价格。要求写出具体的Svelte代码实现,包括定义store以及在组件中使用衍生store显示总价格。
11.3万 热度难度
前端开发Svelte

知识考点

AI 面试

面试题答案

一键面试
<script>
    import { writable, derived } from'svelte/store';

    // 定义购物车商品数量store
    const cartQuantity = writable(5);
    // 定义商品单价store
    const itemPrice = writable(10);

    // 衍生store计算购物车商品总价格
    const totalPrice = derived([cartQuantity, itemPrice], ([$cartQuantity, $itemPrice]) => {
        return $cartQuantity * $itemPrice;
    });
</script>

<div>
    <p>购物车商品总价格: {$totalPrice}</p>
</div>