我找不到让我的代码在 Svelte 中工作的方法。代码涉及对象数组
I can't find a way to make my code work in Svelte. The code involves an array of objects
一行代码,我试了很多方法,就是得不到我想要的结果。
我想要什么?
我想从数组中的第二项开始设置属性 loading = lazy
。我尝试了很多东西,我最后的诱惑是使用 post ID。但不起作用。看看else if
.
<script>
// post props
export let post;
</script>
<!--HTML here-->
<div>
<!-- display posts images -->
{#if post.image}
<!--check if image is not empty -->
<img src={post.image.formats.medium.url} alt={post.title} />
<!-- if id is greater than 2 add loading="lazy" -->
{:else if post.id > 2}
<!-- set lazy images -->
<img src={post.image.formats.medium.url} alt={post.title} loading="lazy" />
{:else}
<!-- if no images then placeholder -->
<img src="images/900x600.png" alt={post.title} loading="lazy" />
{/if}
如果 post.image
是 true
,则 else if
永远不会是 checked/executed。您可以通过始终设置 loading
属性来简化此操作。我个人觉得这更容易理解,因为您实际上想对每个具有 image
.
的元素执行相同的操作
{#if post.image}
<!--check if image is not empty -->
<img src={post.image.formats.medium.url} alt={post.title} loading={post.id > 2 ? 'lazy' : 'eager'} />
{:else}
<!-- if no images then placeholder -->
<img src="images/900x600.png" alt={post.title} loading="lazy" />
{/if}
一行代码,我试了很多方法,就是得不到我想要的结果。
我想要什么?
我想从数组中的第二项开始设置属性 loading = lazy
。我尝试了很多东西,我最后的诱惑是使用 post ID。但不起作用。看看else if
.
<script>
// post props
export let post;
</script>
<!--HTML here-->
<div>
<!-- display posts images -->
{#if post.image}
<!--check if image is not empty -->
<img src={post.image.formats.medium.url} alt={post.title} />
<!-- if id is greater than 2 add loading="lazy" -->
{:else if post.id > 2}
<!-- set lazy images -->
<img src={post.image.formats.medium.url} alt={post.title} loading="lazy" />
{:else}
<!-- if no images then placeholder -->
<img src="images/900x600.png" alt={post.title} loading="lazy" />
{/if}
如果 post.image
是 true
,则 else if
永远不会是 checked/executed。您可以通过始终设置 loading
属性来简化此操作。我个人觉得这更容易理解,因为您实际上想对每个具有 image
.
{#if post.image}
<!--check if image is not empty -->
<img src={post.image.formats.medium.url} alt={post.title} loading={post.id > 2 ? 'lazy' : 'eager'} />
{:else}
<!-- if no images then placeholder -->
<img src="images/900x600.png" alt={post.title} loading="lazy" />
{/if}