Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

334
Visualizações
How can I dynamically add and remove Svelte components in an each block?

Consider that I have some array of objects, from which things may be added and removed. For each object, I want a Svelte component rendered.

If an object is removed, I want its corresponding Svelte component to be destroyed. If an object is added, I want a corresponding Svelte component to be created.

So far I have something naive, like this:

<script>
  let someObjects = [];

  const addObject = (obj) => {
    someObjects = [...someObjects, obj];
  }

  const removeObject = (idx) => {
    someObjects.splice(idx, 1);
    someObjects = someObjects;
  }

  // ...

</script>

{#each someObjects as obj}
  <SomeComponent object={obj} />
{/each}

This doesn't quite work. If you remove an object partway through the array, then in fact, from Svelte's perspective, the final element of the array has been removed, and other elements have just been modified.

This means that Svelte components are retained but with changed object parameters, which breaks any internal state and what-have-you.

How can I force an object halfway through the array to be destroyed, and keep the others from changing? Is the solution perhaps related to bind:this?

about 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

This can be filed away under "read the docs" (thanks Corrl).

Simply ensure your object has some kind of unique identifier as a field, say id, then use a keyed each block:

{#each someObjects as obj (obj.id)}
  <SomeComponent object={obj} />
{/each}
about 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda