Created
March 5, 2022 06:09
-
-
Save vinpac/949e4f5208ae32fc9448cc59d44d682d to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<script> | |
let lista = [ | |
'Pao', | |
'Leite', | |
'Carne', | |
] | |
let novoItem = '' | |
const adicionarItemALista = () => { | |
// lista.push Adiciona, but nao atualiza a lista. Entao o svelte nao entende que a lista mudou | |
// lista = [novoItem] cria sempre uma nova lista, so que com 1 item e apaga os outros | |
// SE o novoItem !== VAZIO | |
if (novoItem !== '') { | |
// Cria uma nova lista, com os items anteriores + o novo item | |
lista = [ | |
// Isso representa os items antigos | |
...lista, | |
// Aqui o novo item | |
novoItem | |
] | |
// Eu apago o que esta escrito no formulario | |
novoItem = '' | |
} | |
} | |
const apague = (qualItem) => { | |
// lista.filter filtra os items na lista que NAO vao passar pela funcao | |
lista = lista.filter( | |
// !== é uma pergunta "Isso NÃO é igual a aquilo" | |
// 1 === 1 -> Verdadeiro | |
// 1 === 2 -> Falso | |
// 1 !== 1 -> Falso | |
// 1 !== 2 -> Verdadeiro | |
(item) => item !== qualItem | |
) | |
} | |
</script> | |
<!-- o preventDefault previne o form de fazer o comportamento padrao. Que é sair da pagina --> | |
<form on:submit|preventDefault={adicionarItemALista}> | |
<input name="novoItem" type="text" bind:value={novoItem} /> | |
<button type="submit"> | |
Adicionar item | |
</button> | |
</form> | |
{#each lista as item} | |
<li> | |
{item} | |
<!-- on:click={ () => apague( AQUI EU PASSO O ITEM ) } --> | |
<!-- Eu to criando uma mini funcao aqui, para so quando clicar, ele remover e saber qual o item tem que remover --> | |
<button on:click={() => apague(item)}> | |
Remover o item: {item} | |
</button> | |
</li> | |
{/each} | |
<p> | |
O primeiro item da lista é {lista[0]} | |
</p> | |
<p> | |
O ultimo item da lista é {lista[lista.length - 1]} | |
</p> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment