Svelte 条件元素类报告为语法错误 [英] Svelte conditional element class reported as a syntax error

查看:24

有些人喜欢做data-selected={index === currentIndex}data=first={index === 0} 和样式基于 [data-selected=true] 选择器.

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.

解决方案

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.

这篇关于Svelte 条件元素类报告为语法错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
前端开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆