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
| API | Description | Access in JS | Access in Template |
|---|---|---|---|
ref(val) | Reactive primitive or object reference | count.value | count (auto-unwrapped) |
reactive(obj) | Reactive object proxy (primitives not allowed) | state.count | state.count |
computed(() => fn) | Cached derived reactive value | doubleCount.value | doubleCount |
watch(source, cb) | Lazy side-effect watch on specific source | watch(count, (newVal) => {}) | N/A |
watchEffect(cb) | Immediate watch auto-tracking dependencies | watchEffect(() => 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
| Directive | Purpose | Shorthand Syntax |
|---|---|---|
v-bind:prop | Dynamic prop or attribute binding | :prop="val" |
v-on:event | Event listener attachment | @click="handleClick" |
v-model | Two-way data binding on form inputs | v-model="text" |
v-if / v-else | Conditional element rendering (DOM insert/remove) | <div v-if="seen"> |
v-show | Toggle element visibility (display: none) | <div v-show="seen"> |
v-for | Render 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
reactiveobject directly destroys reactivity! UsetoRefs(state)ortoRef(state, 'key')if you need to destructure reactive properties.
[!TIP] Always provide a unique
:keyattribute when rendering lists withv-forto enable efficient virtual DOM patching.