问题
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