MST
星途 面试题库

面试题:Svelte中使用Slot与Action构建可复用的模态框交互组件

要求你基于Svelte的Slot和Action特性,开发一个可复用的模态框组件。模态框需要有标题、内容区域和操作按钮区域。标题和内容区域通过Slot传入,操作按钮区域需要有动态交互效果,例如点击关闭按钮时,模态框有淡出动画(利用Action实现),同时在关闭操作中有相应的逻辑回调。
45.1万 热度难度
前端开发Svelte

知识考点

AI 面试

面试题答案

一键面试
  1. 创建模态框组件文件 Modal.svelte
<script>
    import { fade } from 'svelte/transition';

    let isOpen = true;
    let closeCallback = () => {};

    const handleClose = () => {
        isOpen = false;
        closeCallback();
    };
</script>

{#if isOpen}
    <div class="modal" use:fade>
        <div class="modal-header">
            <slot name="header"></slot>
        </div>
        <div class="modal-content">
            <slot name="content"></slot>
        </div>
        <div class="modal-footer">
            <button on:click={handleClose}>关闭</button>
        </div>
    </div>
{/if}

<style>
   .modal {
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background-color: rgba(0, 0, 0, 0.5);
        display: flex;
        justify-content: center;
        align-items: center;
    }

   .modal-header {
        background-color: lightblue;
        padding: 10px;
    }

   .modal-content {
        background-color: white;
        padding: 20px;
    }

   .modal-footer {
        background-color: lightgray;
        padding: 10px;
    }
</style>
  1. 使用模态框组件
<script>
    import Modal from './Modal.svelte';

    const handleModalClose = () => {
        console.log('模态框已关闭');
    };
</script>

<Modal bind:closeCallback={handleModalClose}>
    <h2 slot="header">模态框标题</h2>
    <p slot="content">这是模态框的内容。</p>
</Modal>

在上述代码中:

  • Modal.svelte 组件定义了模态框的结构。通过 Slot 接收标题和内容区域,分别在 slot name="header"slot name="content" 处插入。
  • 使用 fade 过渡效果实现模态框关闭时的淡出动画,这是 Svelte 内置的过渡效果。
  • Modal.svelte 中定义了 handleClose 函数来处理关闭按钮的点击事件,同时执行传入的 closeCallback 回调函数。
  • 在使用模态框组件时,通过 bind:closeCallbackhandleModalClose 函数传递给模态框组件,以便在关闭时执行特定逻辑。