Condition for svelte tag attributes

僤鯓⒐⒋嵵緔 提交于 2019-12-08 10:56:18

问题


How to add attribute inline, without needing to duplicate the anchor tag ? https://svelte.dev/repl/a4e072ca670b481cb5d0360d01d07f27?version=3.12.1

<ul>    
    {#each menu as item}
        <li>
            <a
                {item.prefetch ? 'rel=prefetch' : ''}  
                href="{item.link}">
                {item.title}
            </a>
        </li>
    {/each}
</ul>

I have Error compiling component when:

{item.prefetch ? 'rel=prefetch' : ''}  

Next code works, but not quite what I need:

rel={item.prefetch ? 'prefetch' : ''}  

回答1:


Try using undefined e.g.

            rel={item.prefetch ? 'prefetch' : undefined}  

Which should give you:-

<ul>
<li><a rel="prefetch" href=".">Главная</a> </li>
<li><a href="about.html">О нас</a> </li>
</ul>

See:- https://svelte.dev/repl/31ab5879ed1b457a8a53e3cc70a0749f?version=3.12.1




回答2:


Try this:

<ul>    
  {#each menu as {title, link, prefetch} }
  <li>
     {#if prefetch}
       <a rel="prefetch" href="{link}">{title}</a> 
      {:else}
       <a href="{link}">{title}</a>                  
      {/if}
    </li>
    {/each}
 </ul>

More here: Svelte conditional element class reported as a syntax error

But tenary expressions does not seem to work right now! BUG!



来源:https://stackoverflow.com/questions/58081289/condition-for-svelte-tag-attributes

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!