Svelte conditional element class reported as a syntax error

不打扰是莪最后的温柔 提交于 2019-12-11 05:45:00

问题


I am making an if block per the Svelte Guide for if blocks. It seems simple enough, but Svelte thinks it's a syntax error:

[!] (svelte plugin) ParseError: Unexpected character '#'
public\js\templates\works.html
3:     <div class="slides js_slides">
4:       {#each works as work, index}
5:         <div class="js_slide {#if index === currentIndex }selected{/if} {#if index === 0 }first{/if}">
                                ^
6:           <img src="/images/work/screenshots/{ works[index].slug }-0.{ works[index].imageExtension }"/>
7:         </div>

Why isn't {#if index === currentIndex } considered valid? How can I do a conditional in Svelte?

Not I could create seperate class= blocks for every possible outcome, but that's a massive amount of work.


回答1:


Blocks ({#if..., {#each... etc) can't be used inside attributes — they can only define the structure of your markup.

Instead, the convention is to use ternary expressions...

<div class="
  js_slide
  {index === currentIndex ? 'selected' : ''}
  {index === 0 ? 'first' : ''}
">
  <img src="/images/work/screenshots/{ works[index].slug }-0.{ works[index].imageExtension }"/>
</div>

...or to use a helper:

<!-- language: lang-html -->

<div class="js_slide {getClass(work, index, currentIndex)}">
  <img src="/images/work/screenshots/{ works[index].slug }-0.{ works[index].imageExtension }"/>
</div>

Some people prefer to do things like data-selected={index === currentIndex} and data=first={index === 0}, and style based on [data-selected=true] selectors instead.




回答2:


Since Svelte 2.13 you can also do

<div class:selected={index === currentIndex}>...</div>

See https://svelte.dev/docs#class_name



来源:https://stackoverflow.com/questions/51399018/svelte-conditional-element-class-reported-as-a-syntax-error

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