【问题标题】:Is there a better way in Svelte to include a conditional HTML element在 Svelte 中是否有更好的方法来包含条件 HTML 元素
【发布时间】:2021-01-21 20:46:08
【问题描述】:

我开始经常遇到这个问题。如果布尔值为真,我想在其他元素周围包含一个元素。在下面的示例中,我做了两个 if 语句,但是如果我要包装的代码很大,这将导致不清楚发生了什么。此外,还会有重复的代码。有没有更好的方法来解决这个问题?

<script>
   let boolean = true;
</script>

{#if}
   <img src="source" />
{/if}

{#if}
   <a href="/home">
      <img src="source" />
   </a>
{/if}

【问题讨论】:

    标签: if-statement svelte code-duplication svelte-3


    【解决方案1】:

    如果这是您发现自己经常做的事情,您可以使用 slots 从中制作一个 ConditionalLink 组件。

    <!-- ConditionalLink.svelte -->
    <script>
        export let isWrapped = false;
        export let href;
    </script>
    
    {#if isWrapped}
    <a {href}>
        <slot/>
    </a>
    {:else}
    <slot/>
    {/if}
    

    可以这样使用:

    <script>
        import ConditionalLink from './ConditionalLink.svelte'; 
        let wrapLink = false;
    </script>
    
    <ConditionalLink isWrapped={wrapLink} href="#">
        I'm a link
    </ConditionalLink>
    
    <label><input type="checkbox" bind:checked={wrapLink}> wrap link</label>
    

    【讨论】:

    • 是的。对我来说,何时使用包装组件的试金石测试将是插槽中内容的复杂性。一旦它变得不平凡,我就会将 if 逻辑包装在一个组件中,以避免重复,嗯,不平凡的标记。
    • 谢谢!有一种感觉,这将是最好的方法之一
    猜你喜欢
    • 1970-01-01
    • 2012-04-18
    • 2012-10-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-24
    • 1970-01-01
    相关资源
    最近更新 更多