Skip to content
Tutorials Center
My learning

Topics

Lesson 87 of 87 ยท Practice and Review

Vue.js Cheat Sheet (Vue 3)

A one-page Vue 3 quick reference - template directives, reactivity APIs, component APIs, lifecycle hooks, composable patterns and Options API equivalents, with runnable examples.

This page is a quick reference for the parts of Vue 3 you use every day. It does not teach anything from scratch: each table row links to the lesson that explains it. Keep it open in a tab while you build, and use the two runnable examples as a starting point for your own experiments.

Unless noted, the snippets use the Composition API. Code shown in .vue single-file-component form is read-only (the site has no build step), but every idea also exists as a runnable template-string version in the linked lessons.

Which tool for which job?

flowchart TD
  Q["What do you need?"] --> A["A value that changes"]
  Q --> B["A value derived from other state"]
  Q --> C["A side effect when state changes"]
  A --> A1["ref() - any value, use .value"]
  A --> A2["reactive() - a fixed object, no .value"]
  B --> B1["computed()"]
  C --> C1["watch() - explicit source, old and new value"]
  C --> C2["watchEffect() - tracks automatically"]

Default to ref, derive with computed, and keep watch for side effects.

Template syntax

Syntax Purpose Example
{{ expr }} Text interpolation (escaped) {{ user.name.toUpperCase() }}
v-text Set text content <span v-text="msg"></span>
v-html Set raw HTML (never with untrusted input) <div v-html="trustedHtml"></div>
v-bind:attr or :attr Bind an attribute or prop :href="url", :disabled="busy"
:class / :style Object or array syntax :class="{ active: on, 'is-big': big }"
v-bind="obj" Bind many attributes at once <input v-bind="inputAttrs" />
v-on:event or @event Listen to events @click="add", @input="onInput($event)"
v-model Two-way binding on form inputs and components <input v-model="name" />
v-if / v-else-if / v-else Conditional rendering (adds or removes) <p v-if="ok">Yes</p><p v-else>No</p>
v-show Toggle display: none <p v-show="open">Panel</p>
v-for Loop over arrays, objects, ranges <li v-for="item in items" :key="item.id">
v-slot or #name Slot content (scoped slots receive props) <template #header="{ title }">
v-once Render once, never update <p v-once>{{ fixed }}</p>
v-memo Skip updates unless listed values change <li v-memo="[item.id, item.selected]">
v-pre Do not compile this subtree <span v-pre>{{ raw }}</span>
v-cloak Hide until compiled (CDN use) [v-cloak] { display: none }
key Identity of a node or list item :key="item.id"
ref Template reference <input ref="box" />
<component :is> Render a dynamic component <component :is="current" />

Remember: v-if and v-for do not belong on the same element (filter with computed), and the index is a poor key for lists that change. See common mistakes.

Modifiers

Modifier Where Effect
.prevent, .stop, .self @event preventDefault(), stopPropagation(), only if the target is the element itself
.once, .capture, .passive @event Run once, capture phase, passive listener
.enter, .esc, .tab, .delete, .up, .down... @keyup, @keydown Only for that key
.ctrl, .shift, .alt, .meta, .exact @click, keys Only with those modifier keys
.left, .right, .middle @click Mouse button
.lazy v-model Update on change instead of input
.number v-model Cast to a number
.trim v-model Trim whitespace

More in event handling and v-model.

Directives on one page

Type in the name box (surrounding spaces are trimmed by .trim), change the filter, tick tasks and watch the counts change. The form prints its result on the page and never posts anywhere.

Reactivity APIs

API What it does Notes
ref(x) Reactive box with .value Any type; unwrapped in templates (top level)
reactive(obj) Reactive proxy of an object No primitives; do not replace or destructure
computed(() => ...) Cached derived value Read-only unless you pass { get, set }; keep it pure
readonly(x) Read-only proxy Share state without letting others write
watch(source, cb, opts) Run cb(new, old) when the source changes Source: ref, getter, array of sources; options immediate, deep, once, flush
watchEffect(fn) Run now and re-run when any value it read changes Use the onCleanup argument to undo the previous run
toRef(obj, "key") Ref linked to one property Also accepts a getter
toRefs(state) Object of linked refs Safe to destructure
toValue(x) Read a ref, getter or plain value Used to accept flexible composable inputs
unref(x) / isRef(x) Unwrap / test for a ref
shallowRef(x) Only .value replacement is reactive Big data, external objects; use triggerRef after mutating
markRaw(obj) Never make this object reactive Class instances, third-party objects
nextTick() Resolves after the DOM update await nextTick() before reading the DOM
effectScope() Group effects to stop together Rare; used by libraries
HTML
<script setup>
import { ref, computed, watch } from "vue";

const first = ref("Ada");
const last = ref("Lovelace");
const full = computed(() => first.value + " " + last.value);

watch(full, (now, before) => console.log(before, "->", now));
</script>

See ref, reactive, computed, watch and how reactivity works.

Component APIs

API Purpose Example
defineProps Declare props (compiler macro in <script setup>) const props = defineProps({ title: String })
defineEmits Declare events const emit = defineEmits(["save"]) then emit("save", data)
defineModel Two-way prop for v-model const value = defineModel()
defineExpose Methods and state a parent can reach through a ref defineExpose({ focus })
useSlots, useAttrs Access slots and fallthrough attributes in script
provide / inject Pass data to any descendant provide("theme", theme) / inject("theme")
defineAsyncComponent Load a component lazily defineAsyncComponent(() => import("./Big.vue"))
<Transition>, <TransitionGroup> Animate enter, leave and list moves
<Teleport to="body"> Render content elsewhere in the DOM Modals, tooltips
<KeepAlive> Cache inactive component state include, exclude, max
<Suspense> Wait for async children (experimental)

A typical single-file component, shown read-only because it needs a build tool:

HTML
<script setup>
import { ref } from "vue";

const props = defineProps({ label: { type: String, required: true } });
const emit = defineEmits(["add"]);
const count = ref(0);

function add() {
  count.value++;
  emit("add", count.value);
}
</script>

<template>
  <button type="button" @click="add">{{ props.label }}: {{ count }}</button>
</template>

<style scoped>
button { padding: 0.25rem 0.75rem; }
</style>

Props flow down, events flow up, and a child never writes to a prop. Details in props, emits, slots, provide and inject and single-file components.

Lifecycle hooks

Hook When it runs Typical use
setup() / top of <script setup> Before anything else, once Create state, call composables
onBeforeMount Just before the first render Rarely needed
onMounted After the component is in the DOM Read the DOM, start timers, fetch data, add listeners
onBeforeUpdate Before a re-render Read the DOM state before it changes
onUpdated After a re-render Reaction to DOM changes (prefer watch with flush: "post")
onBeforeUnmount Just before removal Last chance to use the DOM
onUnmounted After removal Clear timers, remove listeners, cancel requests
onActivated, onDeactivated A KeepAlive component shown / hidden Pause and resume work
onErrorCaptured A descendant threw an error Show a fallback

Hooks must be called synchronously during setup (or inside a composable called from setup). See lifecycle hooks.

Composable patterns

A composable is a function named useSomething that returns state and actions. Accept ref, getter or plain value inputs with toValue, and clean up with lifecycle hooks.

Two small composables

useCounter takes step as a ref, so changing the number box changes the next increment without any extra code. useClock starts its timer in onMounted and stops it in onUnmounted, so it cleans up after itself wherever it is used.

Convention Why
Name it useX Signals "stateful, call it in setup"
Return refs, not unwrapped values The caller can destructure without losing reactivity
Accept inputs with toValue Works with refs, getters and plain values
Clean up with onUnmounted or onScopeDispose No leaked timers or listeners
Return an object (or a tuple for tiny helpers) Easy to rename on destructuring

See composables and composable patterns.

App and global APIs

API Purpose
createApp(root) Create an application
app.mount("#el") Mount it (call last)
app.component("Name", def) Register a global component
app.directive("name", def) Register a global directive
app.use(plugin, options) Install a plugin
app.provide(key, value) App-wide provide
app.config.errorHandler Catch errors thrown in components
app.config.globalProperties Add template-accessible properties (use sparingly)

Options API equivalents

Options API Composition API
data() ref() / reactive()
computed: {} computed()
methods: {} Plain functions
watch: {} watch() / watchEffect()
mounted, unmounted... onMounted, onUnmounted...
props, emits defineProps, defineEmits
this.$refs.x A ref with the same name as the ref="x" attribute
provide, inject provide(), inject()
Mixins Composables

Everything in the left column still works in Vue 3. See the Options API.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which API gives you a cached value derived from other reactive state?

    computed() is lazy and cached, and re-evaluates only when a reactive value it read changes.
  2. 2. A composable should accept a ref, a getter or a plain value for an input. Which helper reads all three?

    toValue unwraps a ref, calls a getter and returns a plain value as is, so one code path handles all three.
  3. 3. Where should a timer started in a component's onMounted be stopped?

    onUnmounted runs when the component is removed, which is the place to clear timers, remove listeners and cancel requests.
  4. 4. Which directive keeps an element in the DOM but hides it with CSS?

    v-show toggles display: none. v-if adds and removes the element entirely.
  5. 5. What does the .trim modifier on v-model do?

    .trim strips surrounding whitespace, .lazy syncs on change, and .number casts to a number.

Summary

  • Templates: {{ }}, v-bind, v-on, v-model, v-if / v-show, v-for with a stable key, slots and dynamic components.
  • Reactivity: ref by default, computed for derived values, watch and watchEffect for side effects, toRefs and toValue for flexible inputs.
  • Components: defineProps, defineEmits, defineModel, provide / inject; props down, events up.
  • Lifecycle: create state in setup, touch the DOM in onMounted, clean up in onUnmounted.
  • Composables are useX functions that return refs and clean up after themselves.
  • The Options API maps one-to-one onto the Composition API, and both can coexist.

That is the end of the Vue.js tutorial. Pick a project and build something, or revisit Practice Exercises with Solutions to test yourself.