Created
June 19, 2023 18:32
-
-
Save texastoland/28b35d40a39c3d7000c7e595986c619b to your computer and use it in GitHub Desktop.
Reactivity in Vue compared to Svelte
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 isFancy = true | |
let count = 0 | |
let times = [] | |
// ❎ functions need $: to update | |
$: format = (unfancy, fancy) => (isFancy ? fancy : unfancy) | |
</script> | |
<p> | |
<input type="checkbox" bind:checked={isFancy} /> | |
<label style:display="inline">Fancy output?</label> | |
</p> | |
<!-- ❎ arrays need reassignment to update --> | |
<button on:click={() => (count++, (times = times).push(new Date()))}> | |
{format(count, `Clicked ${count} time${count === 1 ? "" : "s"}`)} | |
</button> | |
<ol> | |
{#each times as time} | |
<li>{format(time.getTime(), time.toLocaleTimeString())}</li> | |
{/each} | |
</ol> |
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 setup> | |
import { ref } from "vue" // can be auto-imported | |
const isFancy = ref(true) | |
const count = ref(0) | |
const times = ref([]) | |
// ✅ functions just work | |
const format = (unfancy, fancy) => (isFancy.value ? fancy : unfancy) | |
</script> | |
<template> | |
<p> | |
<input type="checkbox" v-model="isFancy" /> | |
<label>Fancy output?</label> | |
</p> | |
<!-- ✅ arrays just work --> | |
<button @click="count++, times.push(new Date())"> | |
{{ format(count, `Clicked ${count} time${count === 1 ? "" : "s"}`) }} | |
</button> | |
<ol> | |
<li v-for="time in times"> | |
{{ format(time.getTime(), time.toLocaleTimeString()) }} | |
</li> | |
</ol> | |
</template> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment