Skip to content

Instantly share code, notes, and snippets.

@texastoland
Created June 19, 2023 18:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save texastoland/28b35d40a39c3d7000c7e595986c619b to your computer and use it in GitHub Desktop.
Save texastoland/28b35d40a39c3d7000c7e595986c619b to your computer and use it in GitHub Desktop.
Reactivity in Vue compared to Svelte
<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>
<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