Created
March 22, 2018 19:17
-
-
Save paulocoghi/ce4a490aeba45bb6bffd9660d3578e46 to your computer and use it in GitHub Desktop.
Using #each blocks with store ($) variables defined in runtime
This file contains hidden or 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
<input bind:value='newTodo' placeholder='buy milk'> | |
<button on:click='push("$todos", newTodo)'>add todo</button> | |
<ul> | |
{{#each $todos as todo, i}} | |
<li> | |
<button on:click='splice("$todos", i, 1)'>x</button> | |
{{todo}} | |
</li> | |
{{/each}} | |
</ul> | |
<style> | |
ul { | |
list-style: none; | |
padding: 0; | |
} | |
li button { | |
color: rgb(200,0,0); | |
background: rgba(200,0,0,0.1); | |
border-color: rgba(200,0,0,0.2); | |
padding: 0.2em 0.5em; | |
} | |
</style> | |
<script> | |
import { Store } from 'svelte/store.js'; | |
import { push, splice } from 'svelte-extras'; | |
// If we don't create the store data early (createEarly = false) and | |
// uncomment the line 50, the #each block (from line 5) can't work | |
const createEarly = false; | |
const store = new Store( createEarly ? { todos: [ 'Item 1', 'Item 2' ] } : {} ); | |
export default { | |
data: function () { | |
return { | |
newTodo: '' | |
}; | |
}, | |
methods: { | |
push, | |
splice | |
}, | |
store: () => store, | |
oncreate: function () { | |
this.store.set({ todos: [ 'Item 1', 'Item 2' ] }) | |
} | |
}; | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment