Skip to main content
Quick Reference

Vue.js Cheatsheet

Vue 3 on one page — script setup, template bindings, ref and computed, v-if and v-for, props and emits, composables, Vue Router, Pinia, and the traps that show up in interviews.

10 sections 10 tables 17 code snippets

CLI & a new app

Create and run

npm create vue@latest
npm install
npm run dev
npm run build

What the scaffold gives you

src/main.ts          app startup
src/App.vue          root component
src/router/index.ts  Vue Router
src/stores/          Pinia stores

The current style

ChoiceUse it for
Vue 3Every new app. Vue 2 is end of life
<script setup>The component body. No data() and no this
Vitenpm run dev is usually http://localhost:5173
Single-file componentScript, template, and style in one .vue file
PiniaShared state. Vuex is the old store

This page is Vue 3 with script setup. data(), methods, and this.message are the Options API. You will still see them in old code.

A single-file component

Script

import { ref } from 'vue'

const count = ref(0)

function inc() {
  count.value += 1
}

Template

<button @click="inc">
  Count is {{ count }}
</button>

Where the pieces go

BlockRole
<script setup lang="ts">Runs once per component instance. Top-level bindings are visible in the template
<template>The HTML. Must have one root, or several roots (a fragment)
<style scoped>CSS that applies to this component only
count in the templateA ref is unwrapped. Do not write .value here
count.value in scriptRequired. The ref object itself is not the number

Template bindings

Text, attribute, event, model

<p>{{ name }}</p>
<img :src="photo" :alt="name" />
<button @click="save">Save</button>
<input v-model="query" />
<p :class="{ active: isOn }">Status</p>

Which form

FormMeaning
{{ name }}Text. HTML is escaped
:src or v-bind:srcSet an attribute or DOM property from an expression
@click or v-on:clickListen. The shorthand is @
v-modelTwo-way binding on an input
v-model.trimTrim the string. .number casts it
:class / :styleAn object or an array of classes and styles

v-html inserts raw markup. Use it only for HTML you trust. User text belongs in {{ }}, which escapes it.

ref, reactive & computed

Local state

const count = ref(0)
const doubled = computed(() => count.value * 2)

const user = reactive({
  name: 'Ravi',
  city: 'Hyderabad',
})

Watch a source

watch(count, (value) => {
  console.log(value)
})

watch(() => user.name, (name) => {
  console.log(name)
})

Which container

APIWhen
refA number, string, boolean, or a value you replace entirely
reactiveAn object whose fields you edit. Do not reassign the object
computedA value derived from other state. It is read-only
watchRun code when a source changes. Does not run until it changes
watchEffectRun now, and again when anything it read changes
toRefsSplit a reactive object into refs without losing the connection

user.name = "Ada" updates the view. user = { name: "Ada" } does not, if user came from reactive. Hold the object in a ref when you replace it.

Conditions & lists

Show, hide, repeat

<p v-if="user">Hello, {{ user.name }}</p>
<p v-else>Sign in</p>

<ul>
  <li v-for="item in items" :key="item.id">
    {{ item.name }}
  </li>
</ul>

Directives

DirectiveEffect
v-if / v-else-if / v-elseThe element is created or destroyed. v-else must be the next element
v-showStays in the DOM. Toggles display
v-forRepeats the element. Always add :key
:key="item.id"A stable id. The index is a poor key when the list is reordered or filtered
v-if with v-forDo not put both on the same element. In Vue 3, v-if runs first and cannot see the loop variable

Filter in a computed list, then v-for that list. That keeps the template free of the v-if plus v-for clash.

Props, emits & v-model

In and out

const props = defineProps<{
  name: string
  age?: number
}>()

const emit = defineEmits<{
  save: [name: string]
}>()

function onSave() {
  emit('save', props.name)
}

A component v-model

const title = defineModel<string>({ required: true })

function rename(next: string) {
  title.value = next
}

Parent template

Parent writesChild receives
<UserCard :name="user.name" />props.name
<UserCard @save="store" />emit("save", props.name)
<Editor v-model="title" />defineModel() as a ref
<Editor v-model:title="title" />defineModel("title")
withDefaults(defineProps<...>(), { age: 0 })A default when the prop is omitted

Props are read-only. Changing props.name warns and the parent does not update. Emit an event, or assign to a defineModel() ref.

Composables & lifecycle

A composable

import { onMounted, onUnmounted, ref } from 'vue'

export function useNow() {
  const now = ref(new Date())
  let timer = 0

  onMounted(() => {
    timer = window.setInterval(() => {
      now.value = new Date()
    }, 1000)
  })

  onUnmounted(() => {
    window.clearInterval(timer)
  })

  return { now }
}

When code runs

HookMoment
Script setup itselfInstance is created. This replaces created
onMountedThe DOM for this component exists. Safe place to read a template ref
onUpdatedAfter a render caused by state changes
onUnmountedThe component is gone. Clear timers and listeners here
useNow()Call it in setup, not inside the click handler

A composable is a function that owns state. Name it useSomething and call it from <script setup> so the lifecycle hooks attach to that component.

Vue Router

Leave the page from script

const router = useRouter()
const route = useRoute()

function openUser(id: number) {
  router.push({ name: 'user', params: { id } })
}

Links and the outlet

<RouterLink to="/users">Users</RouterLink>
<RouterView />

Routing pieces

PieceRole
routes in src/routerPath, name, and component
RouterLinkA navigation link. Import it from vue-router
RouterViewWhere the matched page is rendered
useRoute()The current route. params.id is a string
useRouter()Call it in setup, then router.push from a handler
:key="route.params.id" on the pageRemakes the page when the id changes, so old state does not stick

Pinia

A setup store

export const useCartStore = defineStore('cart', () => {
  const items = ref<string[]>([])

  function add(name: string) {
    items.value = [...items.value, name]
  }

  return { items, add }
})

Use it in a component

const cart = useCartStore()
const { items } = storeToRefs(cart)

function addBook() {
  cart.add('Vue')
}

Store rules

RuleWhy
defineStore id is uniqueTwo stores named cart share one instance
Return every state fieldA field you forget is private to the store
storeToRefs(cart)Keeps items reactive after destructuring
const { add } = cartActions can be destructured. State cannot
Call the store in setupThe same rule as useRouter

const { items } = useCartStore() copies the array once. Later add calls will not update items. Destructure state with storeToRefs.

Interview traps

Traps worth memorising

TrapWhat happensPrefer
count += 1 in scriptFails. count is the box, and the binding is constcount.value += 1
{{ count.value }}The template already unwrapped it, so .value is empty{{ count }}
v-if and v-for on one tagIn Vue 3 the v-if cannot see the loop itemA computed list, then v-for
:key="index"DOM state sticks to the slot when the list changes:key="item.id"
Writing to a propVue warns. The parent does not changeAn emit, or defineModel
Reassigning a reactive objectThe template keeps the old proxyA ref, then replace .value
watch(user.name, ...)Watches the string it saw at setupwatch(() => user.name, ...)
useRouter() inside save()Called outside setup, so it throwsCall it at the top of script setup
const { items } = storeLoses reactivitystoreToRefs
v-html with a comment or nameStored HTML runs in the page{{ text }}
Destructuring props on Vue 3.4 and earlierThe values are a one-time copyUse props.name, or Vue 3.5+ where the destructure stays live
No :key on a component in v-forInstances are reused and show the wrong rowA stable id

Script reads .value

function inc() {
  count.value += 1
}

Template does not

<button @click="inc">{{ count }}</button>

How to use this page: scaffold an app with npm create vue@latest, put a ref in <script setup>, and render it. Then add a Pinia store and destructure items both ways so you can see which one updates.