面试题答案
一键面试- 创建模态框组件文件
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>
- 使用模态框组件:
<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:closeCallback
将handleModalClose
函数传递给模态框组件,以便在关闭时执行特定逻辑。