Vue 3 Composition API: Complete Guide

Vue 3 Composition API: Complete Guide

Vue 3 Composition API: Complete Guide

The Composition API is Vue 3's answer to code organisation and reuse in large applications. Instead of organising code by option (data, methods, computed), you organise it by logical concern.

Step 1 — script setup Syntax

The <script setup> compiler macro is the recommended way to use the Composition API — less boilerplate, automatic return of declared variables.

<script setup>
import { ref, computed, onMounted } from 'vue'

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

onMounted(() => console.log('mounted!'))
</script>

<template>
  <button @click="count++">{{ count }} (double: {{ double }})</button>
</template>

Step 2 — Reactive State with ref and reactive

// ref — primitive or single value
const name  = ref('Alice')
const items = ref([])

// reactive — object with multiple properties
const form = reactive({
  email:    '',
  password: '',
  remember: false,
})

// Access in script via .value (ref only)
name.value = 'Bob'
form.email = '[email protected]'

Step 3 — Computed Properties

const search  = ref('')
const products = ref([...])

const filtered = computed(() =>
  products.value.filter(p =>
    p.name.toLowerCase().includes(search.value.toLowerCase())
  )
)

Step 4 — Watchers

import { watch, watchEffect } from 'vue'

// Explicit watcher
watch(search, (newVal) => {
  fetchResults(newVal)
}, { debounce: 300 })

// Auto-tracked watcher
watchEffect(() => {
  document.title = `Results for: ${search.value}`
})

Step 5 — Extracting a Composable

// composables/useSearch.js
export function useSearch(items) {
  const query    = ref('')
  const filtered = computed(() =>
    items.value.filter(i => i.name.includes(query.value))
  )
  return { query, filtered }
}

// Component
const { query, filtered } = useSearch(products)
All Comments