【问题标题】:Svelte conditional element class reported as a syntax errorSvelte 条件元素类报告为语法错误
【发布时间】:2018-07-18 09:56:35
【问题描述】:

我正在根据Svelte Guide for if blocks 制作一个if 块。看起来很简单,但 Svelte 认为是语法错误:

[!] (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>

为什么{#if index === currentIndex } 无效?如何在 Svelte 中执行条件语句?

我不能为每个可能的结果创建单独的class= 块,但这是大量的工作。

【问题讨论】:

  • 块({#if...{#each... 等)不能在属性中使用。相反,约定是使用三元表达式({index === currentIndex ? 'selected' : ''} {index === 0 ? 'first' : ''},或使用助手(例如class={getClass(work, index, currentIndex)})。有些人更喜欢使用data-selected={index === currentIndex} data=first={index === 0}
  • 谢谢 — 已将我的评论移至答案

标签: javascript css svelte


【解决方案1】:

块({#if...{#each... 等)不能用于属性内部——它们只能定义标记的结构。

相反,约定是使用三元表达式...

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

...或使用助手:

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

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

有些人更喜欢使用data-selected={index === currentIndex}data=first={index === 0} 之类的东西,而是使用基于[data-selected=true] 选择器的样式。

【讨论】:

【解决方案2】:

从 Svelte 2.13 开始你也可以这样做

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

https://svelte.dev/docs#class_name

【讨论】:

    【解决方案3】:

    https://svelte.dev/docs#class_name 所述,在class

    中操作if else需要额外的JS变量

    这是一个示例,其中 each 循环从 a 迭代到 b 并且当 iftrue 将应用 css

    {#each Array.from(Array(b+1).keys()).slice(a) as i }
    
        <div class="{ i===4 ? "border-l-2 border-blue-500" : ""}  p-3 space-y-4">
         some sample text
        </div>
    {/each}
    

    示例(1 到 15):

    {#each Array.from(Array(15+1).keys()).slice(1) as i }
    
        <div class="{ i===3 ? "border-l-2 border-blue-500" : ""}  p-3 space-y-4">
         some sample text
        </div>
    {/each}
    

    【讨论】:

      猜你喜欢
      • 2016-12-13
      • 2016-09-04
      • 2013-11-28
      • 2019-10-10
      • 1970-01-01
      • 2018-05-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多