英文:
Duplicate elements in #each Svelte
问题
您可以通过在循环相关文章时使用一个额外的集合来跟踪已经添加的文章,以避免重复。以下是修改后的代码:
<script>
import { getMarkdownPosts } from '$lib/utils/getPosts';
let posts = getMarkdownPosts();
let addedArticles = []; // 用于跟踪已经添加的文章
export let currentPostTitle, currentPostTags;
function hasArticleBeenAdded(slug) {
return addedArticles.includes(slug);
}
function markArticleAsAdded(slug) {
addedArticles.push(slug);
}
</script>
{#await posts}
Loading...
{:then posts}
Related posts
<ul>
{#each posts as {slug, meta: {title, tags, published}}}
{#if published}
{#if currentPostTitle != title && !hasArticleBeenAdded(slug)}
{#each tags as tag}
<!-- {#if index === 1 } -->
{#if currentPostTags.includes(tag)}
<li><a href="/blog/{slug}"><h4>{title}</h4></a></li>
{#each posts as post}
{#if post.slug === slug}
{#exec markArticleAsAdded(slug)}
{/if}
{/each}
{/if}
<!-- {/if} -->
{/each}
{/if}
{/if}
{/each}
</ul>
{/await}
这样,您将使用 addedArticles
数组来跟踪已经添加的文章的 slug
,并且只有当文章未被添加时才添加它们到相关文章列表中。当您添加文章后,使用 markArticleAsAdded(slug)
函数来将文章标记为已添加,以确保不会重复列出相同的文章。
英文:
I have a component on related posts on the Svelte website. It works, but the problem is that it duplicates the articles in the block. That is, for example, if I have three identical tags contained in two articles, then in each of these articles another article in the related posts block will be listed three times.
<script>
import { getMarkdownPosts } from '$lib/utils/getPosts'
let posts = getMarkdownPosts()
export let currentPostTitle, currentPostTags
</script>
{#await posts}
Loading...
{:then posts}
Related posts
<ul>
{#each posts as {slug, meta: {title, tags, published}}}
{#if published}
{#if currentPostTitle != title}
{#each tags as tag}
<!-- {#if index === 1 } -->
{#if currentPostTags.includes(tag)}
<li><a href="/blog/{slug}"><h4>{title}</h4></a></li>
{/if}
<!-- {/if} -->
{/each}
{/if}
{/if}
{/each}
</ul>
{/await}
How can I change this code so that this does not happen?
答案1
得分: 0
我考虑了一下,重新编写了这个组件。现在它工作得很好。
英文:
I thought about it and rewrote the component. It's working fine now
<script>
import { getMarkdownPosts } from '$lib/utils/getPosts'
import { onMount } from 'svelte'
let posts = []
let relatedPosts = []
export let currentPostTitle, currentPostTags
onMount(async () => {
posts = await getMarkdownPosts()
filterRelatedPosts()
})
function filterRelatedPosts() {
relatedPosts = posts.filter(post => {
// Exclude the current post and duplicates based on tags
return (
post.meta.title !== currentPostTitle && post.meta.published &&
currentPostTags.some(tag => post.meta.tags.includes(tag))
)
})
}
</script>
{#if relatedPosts.length > 0}
Related posts
<ul>
{#each relatedPosts as { slug, meta: { title } }}
<li><a href="/blog/{slug}"><h4>{title}</h4></a></li>
{/each}
</ul>
{:else}
No related posts found.
{/if}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论