Vue 3 + TypeScript Cheat Sheet

Valid for Vue 3.5 with <script setup lang="ts"> (Composition API). The blue labels show the Vue version in which a feature was introduced, red labels mark discouraged or deprecated APIs.

Project setup

What How
Create a project
npm create vue@latest   # choose TypeScript, Router, Pinia, Vitest
cd my-app && npm install && npm run dev
Type check (.vue files)
npx vue-tsc --noEmit        # tsc cannot read .vue files
IDE: Vue (Official) extension, not Vetur.
Entry point
import { createApp } from 'vue';
import { createPinia } from 'pinia';
import App from './App.vue';
import router from './router';

createApp(App).use(createPinia()).use(router).mount('#app');
Single File Component
<script setup lang="ts">
  // logic
</script>

<template>
  <!-- markup -->
</template>

<style scoped>
  /* CSS only for this component */
</style>

Reactivity

What How
ref (primitives and objects)
import { ref, type Ref } from 'vue';

const count: Ref<number> = ref(0);
const user = ref<User | null>(null);   // explicit generic if the type can't be inferred

count.value++;                          // .value in script
// in the template: {{ count }}  (no .value)
reactive (objects only)
import { reactive } from 'vue';

const form = reactive<{ name: string; age: number }>({ name: '', age: 0 });
form.age = 42;
// do not destructure (loses reactivity) and do not replace the whole object
computed
import { computed } from 'vue';

const double = computed(() => count.value * 2);          // ComputedRef<number>, read-only
const full = computed<string>({
  get: () => first.value + ' ' + last.value,
  set: (v) => { [first.value, last.value] = v.split(' '); },
});
watch
import { watch } from 'vue';

watch(count, (newVal, oldVal) => { ... });
watch(() => form.name, (name) => { ... });             // getter for reactive props
watch([a, b], ([newA, newB]) => { ... });               // multiple sources
watch(source, cb, { immediate: true, deep: true });
watchEffect
watchEffect(() => console.log(count.value));            // tracks dependencies automatically, runs immediately
onWatcherCleanup
Vue 3.5
import { watch, onWatcherCleanup } from 'vue';

watch(id, (newId) => {
  const controller = new AbortController();
  fetch(`/api/${newId}`, { signal: controller.signal });
  onWatcherCleanup(() => controller.abort());
});
shallowRef, toRef, toRefs, toValue
const big = shallowRef(hugeObject);          // only .value replacement is tracked
const { name, age } = toRefs(form);          // destructure reactive and keep reactivity
const nameRef = toRef(props, 'name');
toValue(maybeRefOrGetter);                   // unwraps ref / getter / plain value

Template syntax

What How
Interpolation / attribute binding
<p>{{ message.toUpperCase() }}</p>
<img :src="imageUrl" :alt="title">            <!-- v-bind shorthand : -->
<div :class="{ active: isActive, 'text-bold': bold }" :style="{ color }"></div>
<comp v-bind="objectOfProps" />
Events
<button @click="count++">+1</button>               <!-- v-on shorthand @ -->
<button @click="onClick($event, id)"></button>
<form @submit.prevent="save"></form>
<input @keyup.enter="send">
// typed handler
function onInput(e: Event) {
  const value = (e.target as HTMLInputElement).value;
}
v-if, v-else-if, v-else, v-show
<p v-if="state === 'loading'">Loading...</p>
<p v-else-if="state === 'error'">Error</p>
<p v-else>Done</p>
<p v-show="visible">toggles CSS display only</p>
v-for
<li v-for="(item, index) in items" :key="item.id">{{ index }}: {{ item.name }}</li>
<li v-for="(value, key) in object" :key="key"></li>
<li v-for="n in 5" :key="n"></li>
<!-- always set :key; do not combine v-for and v-if on the same element -->
v-model
<input v-model="text">
<input v-model.trim.lazy="text">
<input v-model.number="age">
<input type="checkbox" v-model="checked">
<select v-model="selected"><option value="a">A</option></select>
Template refs (DOM access)
Vue 3.5
import { useTemplateRef, onMounted } from 'vue';

const input = useTemplateRef<HTMLInputElement>('input');   // matches ref="input"
onMounted(() => input.value?.focus());

// template: <input ref="input">
Component ref
import MyComp from './MyComp.vue';
const comp = useTemplateRef<InstanceType<typeof MyComp>>('comp');

Components: props, emits, v-model, slots

What How
defineProps (type-based)
interface Props {
  title: string;
  count?: number;
  items?: string[];
}
const props = defineProps<Props>();
// props are read-only. Destructuring is reactive since Vue 3.5:
const { title, count = 0 } = defineProps<Props>();
Default values for objects / arrays
(only needed before 3.5 destructuring)
const props = withDefaults(defineProps<Props>(), {
  count: 0,
  items: () => [],          // factory function for reference types
});
defineEmits (typed)
const emit = defineEmits<{
  save: [payload: User];            // named tuple syntax
  close: [];
}>();

emit('save', user);
defineModel (two-way binding)
Vue 3.4
// child
const model = defineModel<string>({ required: true });
const checked = defineModel<boolean>('checked', { default: false });   // v-model:checked
model.value = 'new value';                                             // emits update:modelValue

// parent
<Child v-model="name" v-model:checked="flag" />
defineSlots (typed slots)
defineSlots<{
  default(props: { item: Item }): any;
  header?(): any;
}>();

<!-- child -->
<slot :item="item">fallback content</slot>
<slot name="header" />

<!-- parent -->
<Child>
  <template #default="{ item }">{{ item.name }}</template>
  <template #header>Title</template>
</Child>
defineExpose
// <script setup> components are closed by default
defineExpose({ reset, focus });
defineOptions
defineOptions({ name: 'MyButton', inheritAttrs: false });
Generic components
<script setup lang="ts" generic="T extends { id: number }">
defineProps<{ items: T[]; selected: T }>();
</script>
useId
Vue 3.5
const id = useId();                  // stable unique id, SSR-safe
// <label :for="id">  <input :id="id">

Lifecycle hooks

Hook When
setup() / <script setup> Component creation (replaces beforeCreate / created)
onBeforeMount, onMounted Before / after the DOM is created. Template refs are available in onMounted.
onBeforeUpdate, onUpdated Before / after a reactive change re-renders the DOM
onBeforeUnmount, onUnmounted Clean up timers, listeners, subscriptions
onErrorCaptured Error from a descendant component
onActivated, onDeactivated Component inside <KeepAlive>
nextTick() await nextTick() waits until the DOM has been updated

Provide / Inject (typed)

What How
Shared key
import type { InjectionKey, Ref } from 'vue';
export const userKey: InjectionKey<Ref<User>> = Symbol('user');
Provide / inject
provide(userKey, user);                          // ancestor

const user = inject(userKey);                    // Ref<User> | undefined
const user2 = inject(userKey, defaultUser);      // with default
const user3 = inject(userKey) as Ref<User>;     // or throw an error if missing

Composables

What How
Reusable stateful logic (use... naming)
// composables/useFetch.ts
import { ref, toValue, watchEffect, type MaybeRefOrGetter } from 'vue';

export function useFetch<T>(url: MaybeRefOrGetter<string>) {
  const data = ref<T | null>(null);
  const error = ref<Error | null>(null);
  const loading = ref(false);

  watchEffect(async () => {
    loading.value = true;
    try {
      const response = await fetch(toValue(url));
      data.value = await response.json() as T;
    } catch (e) {
      error.value = e as Error;
    } finally {
      loading.value = false;
    }
  });

  return { data, error, loading };
}

// usage
const { data, loading } = useFetch<User[]>('/api/users');
Async component / lazy loading
import { defineAsyncComponent } from 'vue';
const Heavy = defineAsyncComponent(() => import('./Heavy.vue'));

Vue Router 4

What How
Router definition
import { createRouter, createWebHistory, type RouteRecordRaw } from 'vue-router';

const routes: RouteRecordRaw[] = [
  { path: '/', name: 'home', component: HomeView },
  { path: '/users/:id', name: 'user', component: () => import('./UserView.vue'), props: true },
  { path: '/:pathMatch(.*)*', component: NotFound },
];

export default createRouter({ history: createWebHistory(), routes });
Template
<RouterLink :to="{ name: 'user', params: { id: 7 } }">User</RouterLink>
<RouterView />
In script
import { useRoute, useRouter } from 'vue-router';

const route = useRoute();                 // reactive, read: route.params.id, route.query
const router = useRouter();
router.push({ name: 'home' });
router.replace('/login');
router.back();
Navigation guards
router.beforeEach((to, from) => {
  if (to.meta.requiresAuth && !isLoggedIn()) return { name: 'login' };
  // return nothing / true to continue, false to cancel
});

// in a component
onBeforeRouteLeave(() => confirmLeave());
onBeforeRouteUpdate((to) => { ... });

Pinia (state management)

What How
Setup store (recommended)
import { defineStore } from 'pinia';
import { ref, computed } from 'vue';

export const useCounterStore = defineStore('counter', () => {
  const count = ref(0);                         // state
  const double = computed(() => count.value * 2);   // getter
  function increment() { count.value++; }      // action
  return { count, double, increment };
});
Use a store
import { storeToRefs } from 'pinia';

const store = useCounterStore();
const { count, double } = storeToRefs(store);   // state + getters keep reactivity
const { increment } = store;                    // actions can be destructured directly

Useful TypeScript types

Type Meaning
Ref<T>, ShallowRef<T> Result of ref() / shallowRef()
ComputedRef<T>, WritableComputedRef<T> Result of computed()
MaybeRef<T>, MaybeRefOrGetter<T> Parameters of composables that accept values, refs or getters
InjectionKey<T> Typed key for provide / inject
PropType<T> Runtime props declaration (only needed without type-based defineProps)
Component, DefineComponent Type of a component (e.g. for dynamic <component :is>)
ComponentPublicInstance, InstanceType<typeof Comp> Type of a component instance (template refs)
ExtractPropTypes<T>, ComponentProps<typeof Comp> Props of a component as a type

Testing with Vitest and Vue Test Utils

What How
Component test (Given-When-Then)
import { describe, it, expect } from 'vitest';
import { mount } from '@vue/test-utils';
import Counter from './Counter.vue';

describe('Counter', () => {
  it('givenInitialCount_whenButtonClicked_thenCountIsIncremented', async () => {
    // given
    const wrapper = mount(Counter, { props: { initial: 1 } });

    // when
    await wrapper.find('button').trigger('click');

    // then
    expect(wrapper.text()).toContain('2');
    expect(wrapper.emitted('changed')).toHaveLength(1);
  });
});
Pinia in tests
import { setActivePinia, createPinia } from 'pinia';
beforeEach(() => setActivePinia(createPinia()));
Run
npx vitest          # watch mode
npx vitest run      # once, e.g. in CI

Pitfalls

Problem Solution
Forgot .value in script Refs need .value in script, but not in the template (top-level refs only).
Destructuring reactive() or a store loses reactivity Use toRefs() / storeToRefs().
Mutating a prop Props are one-way. Emit an event or use defineModel.
v-for without :key or with the index as key in changing lists Use a stable unique id.
Template ref is null Only available after onMounted, and not while a v-if hides the element.
Side effects in computed Computed must be pure. Use watch for side effects.
Options API (data(), methods, this) discouraged Still works, but new code should use <script setup lang="ts">. Vuex is replaced by Pinia.