【问题标题】:Best practice on creating a reusable Modal component in Svelte?在 Svelte 中创建可重用的模态组件的最佳实践?
【发布时间】:2021-08-23 04:58:46
【问题描述】:

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

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

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

App.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} />

Modal.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);

【问题讨论】:

    标签: components svelte


    【解决方案1】:

    我找到了问题的答案:使用 svelte:component 制作动态组件。在这里回复: https://svelte.dev/repl/4624e3f0f3684ddcb2e2da10592f6df1?version=3.38.2

    【讨论】:

      猜你喜欢
      • 2016-10-20
      • 1970-01-01
      • 2012-04-28
      • 2015-07-23
      • 1970-01-01
      • 1970-01-01
      • 2019-04-29
      • 1970-01-01
      • 2018-10-09
      相关资源
      最近更新 更多