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.
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>
// 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]'
const search = ref('')
const products = ref([...])
const filtered = computed(() =>
products.value.filter(p =>
p.name.toLowerCase().includes(search.value.toLowerCase())
)
)
import { watch, watchEffect } from 'vue'
// Explicit watcher
watch(search, (newVal) => {
fetchResults(newVal)
}, { debounce: 300 })
// Auto-tracked watcher
watchEffect(() => {
document.title = `Results for: ${search.value}`
})
// 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