vue.joedoe.dev

Cheat sheet

Vue 3 with <script setup> on one page: 42 things I look up again and again, each with a line on when to use it.

Reactivity

  • const count = ref(0)
    count.value++

    The usual one. .value in script, none in the template.

  • const form = reactive({ name: '', age: 0 })

    For objects. Don't destructure it or you lose reactivity.

  • const big = shallowRef(hugeArray)
    big.value = [...big.value, item]

    Only reacts when .value is replaced. For big lists or data you never mutate inside.

  • const total = computed(() => items.value.length)

    Derived and cached: only recomputed when what it reads changes.

  • watch(id, async (now, before) => { … }, { immediate: true })

    For side effects with the new and old value. immediate also runs it at the start.

  • watch(() => props.user.id, load)

    To watch a single property, pass it as a getter.

  • watchEffect(() => document.title = title.value)

    Subscribes to whatever it reads. Handy for syncing with the outside world.

  • const { x, y } = toRefs(state)

    Destructure a reactive without breaking it.

  • const value = toValue(maybeRefOrGetter)

    In composables: accepts a value, a ref or a getter, and gives you the value.

  • const safe = readonly(state)

    To expose state nobody outside should touch.

  • await nextTick()

    Waits for the DOM to reflect the last change (to measure or focus).

<script setup> macros

  • const { size = 'md', items } = defineProps<{
      size?: 'sm' | 'md'
      items: Item[]
    }>()

    Typed props with defaults while destructuring (3.5).

  • const emit = defineEmits<{
      save: [item: Item]
      close: []
    }>()

    Typed events with the tuple syntax.

  • const open = defineModel<boolean>()
    const q = defineModel<string>('query')

    v-model and v-model:query, one line each.

  • defineSlots<{ default(p: { item: T }): any }>()

    Types what the slots receive.

  • defineExpose({ focus })

    The only thing a parent sees through a ref to the component.

  • defineOptions({ name: 'Card', inheritAttrs: false })

    Component options without a second <script>.

  • <script setup lang="ts" generic="T">

    Generic components: T is inferred from the props.

Lifecycle

  • onMounted(() => el.value?.focus())

    The DOM exists. window, localStorage and measuring go here: it never runs on the server.

  • onUnmounted(() => observer.disconnect())

    Clean up what you opened: listeners, timers, observers.

  • onUpdated(() => …)

    After every re-render. You rarely need it.

  • onActivated(() => …)
    onDeactivated(() => …)

    Inside <KeepAlive>: shown again or hidden.

  • onErrorCaptured((err) => { report(err); return false })

    Catches children's errors. false stops them bubbling further.

Template

  • <li v-for="item in items" :key="item.id">

    Always with a stable :key, never the index if the list reorders.

  • <input v-model.trim.lazy="name">
    <input v-model.number="age" type="number">

    Modifiers: trim strips spaces, lazy waits for change, number converts.

  • <form @submit.prevent="save">
    <input @keyup.enter="search">

    Event modifiers: goodbye event.preventDefault().

  • <div v-show="open">

    Only toggles display. Better than v-if for things opened often.

  • <Child v-bind="$attrs" />
    <Child v-bind="{ id, title }" />

    Pass a whole object of attributes at once.

  • <template #header="{ title }">

    A named slot with data from the child.

  • <div ref="box">
    const box = useTemplateRef('box')

    Element refs by name (3.5), without the variable sharing the name.

  • <p :class="{ active: isOn }" :style="{ '--size': size + 'px' }">

    Classes by object and custom properties from state.

Built-in components

  • <Transition name="fade"><p v-if="ok" /></Transition>

    fade-enter-from, -active, -leave-to… classes to enter and leave.

  • <TransitionGroup name="list" tag="ul">

    For lists; with .list-move, reordering animates too.

  • <Teleport to="body"><dialog>…</dialog></Teleport>

    Renders content elsewhere in the DOM: modals, toasts, tooltips.

  • <KeepAlive :max="5"><component :is="tab" /></KeepAlive>

    Keeps the state of components you hide.

  • <Suspense>
      <AsyncPage />
      <template #fallback>Cargando…</template>
    </Suspense>

    Waits for components with await in setup. Still marked experimental.

  • const Chart = defineAsyncComponent(() => import('./Chart.vue'))

    Loads a heavy component only when it's used.

New in Vue 3.5

  • const id = useId()

    Unique ids, stable between server and browser, for label/for and aria.

  • watch(q, () => {
      const c = new AbortController()
      onWatcherCleanup(() => c.abort())
    })

    Clean up a watcher without the third onCleanup argument.

  • watch(source, cb, { deep: 1 })

    deep takes a number: how many levels to watch.

  • const { stop, pause, resume } = watch(…)

    Watchers can be paused and resumed.

  • <Teleport defer to="#later">

    defer: the target may appear later in the same template.

For everything else, the official docs ↗

↑↓ move · ↵ open · esc close