Vue 3 Composition API Cheat Sheet

Quick reference guide for Vue 3: Composition API, script setup, reactivity (ref/reactive), computed, watch, and directives.

Modern Frontend
vue
vue3
frontend

Vue 3 is a progressive JavaScript framework for building user interfaces. The Composition API with <script setup> provides flexible code organization and full TypeScript support.

Reactivity Core Functions

Vue 3 uses Proxy-based reactivity to track and update state automatically.

Table
APIDescriptionAccess in JSAccess in Template
ref(val)Reactive primitive or object referencecount.valuecount (auto-unwrapped)
reactive(obj)Reactive object proxy (primitives not allowed)state.countstate.count
computed(() => fn)Cached derived reactive valuedoubleCount.valuedoubleCount
watch(source, cb)Lazy side-effect watch on specific sourcewatch(count, (newVal) => {})N/A
watchEffect(cb)Immediate watch auto-tracking dependencieswatchEffect(() => console.log(count.value))N/A

`<script setup>` Syntax Example

vue
<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'

// Reactive state
const count = ref<number>(0)
const text = ref<string>('')

// Computed property
const doubleCount = computed(() => count.value * 2)

// Methods
function increment() {
  count.value++
}

// Lifecycle hook
onMounted(() => {
  console.log('Component mounted successfully')
})
</script>

<template>
  <div class="card">
    <p>Count: {{ count }} (Double: {{ doubleCount }})</p>
    <button @click="increment">Increment</button>
    <input v-model="text" placeholder="Type something..." />
  </div>
</template>

Template Directives Syntax

Table
DirectivePurposeShorthand Syntax
v-bind:propDynamic prop or attribute binding:prop="val"
v-on:eventEvent listener attachment@click="handleClick"
v-modelTwo-way data binding on form inputsv-model="text"
v-if / v-elseConditional element rendering (DOM insert/remove)<div v-if="seen">
v-showToggle element visibility (display: none)<div v-show="seen">
v-forRender list of items<li v-for="item in items" :key="item.id">

Component Props and Emits

vue
<script setup lang="ts">
// Define props with TypeScript types
const props = defineProps<{
  title: string
  count?: number
}>()

// Define emitted events
const emit = defineEmits<{
  (e: 'update', value: number): void
  (e: 'close'): void
}>()

function handleClose() {
  emit('close')
}
</script>

Common Pitfalls & Tips

[!WARNING] Destructuring a reactive object directly destroys reactivity! Use toRefs(state) or toRef(state, 'key') if you need to destructure reactive properties.

[!TIP] Always provide a unique :key attribute when rendering lists with v-for to enable efficient virtual DOM patching.