首页 > 解决方案 > 在 Svelte 中创建可重用的模态组件的最佳实践?

问题描述

我一直无法理解在 Svelte 中创建可重用模态组件的最佳方法。我想拥有 Modal 组件,我可以在其中轻松地以可扩展的方式传递其他组件。当我单击背景时,它应该破坏模式和里面的内容。

我在这里创建了一个带有工作版本的 REPL,但想知道这是否是实现此目的的复杂方式: https ://svelte.dev/repl/9180dd40e7304fc78d175cf4535a6423?version=3.38.2

此方法有效,但我不知道这是否是建议的方法(我对 Svelte 和组件库都是新手)。

应用程序.js

<script>
    import Modal from './Modal.svelte'
    import Component1 from './Component1.svelte'
    import Component2 from './Component2.svelte'
    import {showModal} from './store.js'
    
    let showC1, showC2 = false;
    
    function toggleModal() {
        $showModal = !$showModal;
    }
    
    function toggleC1() {
        toggleModal();
        showC1 = !showC1;
    }
    
    function toggleC2() {
        toggleModal();
        showC2 = !showC2;}
</script>

<button on:click={toggleC1}>
    Toggle Component 1
</button>
<button on:click={toggleC2}>
    Toggle Component 2
</button>

<Component1 {showC1} on:click={toggleC1}  />
<Component2 {showC2} on:click={toggleC2} />

模态.svelte

<script>
    import {showModal} from './store.js'
</script>

{#if $showModal}
<div on:click|self class='modal'>
    <div class='content'>
        <slot />
    </div>
</div>
{/if}

<style>
    .modal {
        background-color: rgba(0, 0, 0, 0.589);
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        opacity: 0.7;
        display: flex;
        justify-content: center;
        align-items: center;
    }
    
    .content {
        background-color: white;
        width: 20em;
        height: 20em;
    }
</style>

Component1.svelte

<script>
    import Modal from './Modal.svelte'
    export let showC1;
</script>

{#if showC1}
    <Modal on:click>
        <div>
            This is some content...
        </div>
        <button on:click>
            close
        </button>
    </Modal>
{/if}

Component2.svelte

<script>
    import Modal from './Modal.svelte'
    export let showC2;
</script>

{#if showC2}
    <Modal on:click>
        <div>
            ...And some more content
        </div>
        <button on:click>
            close
        </button>
    </Modal>
{/if}

store.js

import { writable } from "svelte/store";
export const showModal = writable(false);

标签: componentssvelte

解决方案


我想出了一个问题的答案:使用 svelte:component 制作动态组件。REPL 在这里: https ://svelte.dev/repl/4624e3f0f3684ddcb2e2da10592f6df1?version=3.38.2


推荐阅读