The Composition API is the modern way to write Vue 3 components. With <script setup> it needs less code than the older Options API and lets you reuse logic easily. Here are the three building blocks you will use every day.
ref: a reactive value
ref wraps a single value so Vue can track changes. In the script you read and write it through .value; in the template Vue unwraps it for you.
<script setup>
import { ref } from 'vue'
const count = ref(0)
function increment() { count.value++ }
</script>
<template>
<button @click="increment">Clicked {{ count }} times</button>
</template>reactive: a reactive object
import { reactive } from 'vue'
const form = reactive({ name: '', email: '' })
form.name = 'Asha'reactive makes an object deeply reactive and needs no .value. Do not replace the whole object (form = {...}) or destructure its properties into plain variables, because the link to Vue is lost. Many developers simply use ref for everything, which avoids these traps.
computed: values derived from other values
import { ref, computed } from 'vue'
const price = ref(250)
const qty = ref(3)
const total = computed(() => price.value * qty.value)A computed value is cached and recalculated only when what it depends on changes. Use it for anything you can calculate from other state, such as totals, filtered lists and formatted text.
watch: run code when something changes
import { watch } from 'vue'
watch(qty, (newVal, oldVal) => {
console.log(`Quantity changed from ${oldVal} to ${newVal}`)
})Use watch for side effects such as saving to storage or calling an API. For calculating a value, prefer computed.
Lifecycle hooks
import { onMounted, onUnmounted } from 'vue'
onMounted(() => window.addEventListener('resize', onResize))
onUnmounted(() => window.removeEventListener('resize', onResize))Reusing logic: composables
A composable is just a function that uses these tools and returns state. Move repeated logic, such as tracking the mouse or fetching data, into functions named useSomething(), and call them from any component.
// useCounter.js
import { ref } from 'vue'
export function useCounter(start = 0) {
const count = ref(start)
const increment = () => count.value++
return { count, increment }
}ref or reactive?
Both work, and the choice is partly style. ref works for primitives and objects alike and keeps the same pattern everywhere (.value in the script). reactive reads a little cleaner for grouped form data, but it cannot hold a primitive directly and loses reactivity if you destructure it. A safe approach is to use ref by default and reactive where an object genuinely feels natural. When you need to destructure a reactive object, use toRefs.
Props and emits with script setup
<script setup>
const props = defineProps({ title: String, count: { type: Number, default: 0 } })
const emit = defineEmits(['update'])
function save() {
emit('update', props.count + 1)
}
</script>Props flow down from parent to child and are read-only. A child tells its parent about changes by emitting events. For two-way binding on a component, Vue 3.4 and later offers defineModel.
Fetching data
<script setup>
import { ref, onMounted } from 'vue'
const posts = ref([])
const loading = ref(true)
const error = ref(null)
onMounted(async () => {
try {
const res = await fetch('/api/posts')
posts.value = await res.json()
} catch (e) {
error.value = e
} finally {
loading.value = false
}
})
</script>Computed versus watch versus methods
- Use computed to derive a value; it is cached.
- Use a method when you need to run something on an event or pass arguments.
- Use watch or watchEffect only for side effects, such as saving to storage, logging or calling an API.
Sharing state between components
For small apps, a composable that holds a ref outside the function can be shared by importing it in several components. For larger apps, use Pinia, the official state management library. It offers stores, devtools support and good TypeScript support.
// stores/cart.js
import { defineStore } from 'pinia'
export const useCartStore = defineStore('cart', {
state: () => ({ items: [] }),
getters: { count: (s) => s.items.length },
actions: { add(item) { this.items.push(item) } },
})Common beginner mistakes
- Forgetting
.valuein the script section. - Mutating a prop inside the child instead of emitting an event.
- Using
v-ifandv-fortogether on the same element; filter the list with a computed value instead. - Missing the
keyattribute inv-forlists. - Doing heavy work inside the template instead of a computed property.
Covering financial markets, commodity rates, and practical technology insights for India. Researched and fact-checked in accordance with our Editorial Policy.
Related & Trending Stories
Recommended based on your reading interest

