My account

Vue fundamentals

Vue tracks which reactive values your code reads and re-runs that code when one of them changes. Use ref for state, computed for values you can calculate, and watch only for side effects like a network call. Data goes down as props and changes come back up as events, so every piece of data has one owner.

Not reviewedWritten with AI helpReading time: 16 minOnline shop exampleVue 3.5 code

Author: bezzad

Contents

The problem: a cart badge that does not update

Our online shop has a small cart badge in the header. A new teammate wrote it like this:

<script setup lang="ts">
import { reactive } from 'vue'

const cart = reactive({ count: 0 })
const { count } = cart // a plain number now

function addToCart() {
  cart.count++
}
</script>

<template>
  <button type="button" @click="addToCart">Add to cart</button>
  <span class="badge">{{ count }}</span>
</template>
  1. The user clicks “Add to cart”. The cart count really changes to 1.
  2. The badge still shows 0. Nothing on the screen updates.
  3. There is no error in the console. The code looks fine at first sight.

Vue did not fail here. The code broke the link between the data and the screen. To see why, you need to know how Vue reactivity works. Almost every Vue interview question comes back to this.

A single-file component

A Vue component usually lives in one .vue file with three parts:

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

defineProps<{ name: string; price: number }>()

const quantity = ref(1)
</script>

<template>
  <article class="card">
    <h3>{{ name }}</h3>
    <p>{{ price * quantity }} USD</p>
    <button type="button" @click="quantity++">One more</button>
  </article>
</template>

<style scoped>
.card {
  border: 1px solid #ddd;
  padding: 1rem;
}
</style>
  1. The script setup block is the logic. Everything you declare here, like variables, functions and imports, can be used in the template. This is the Composition API.
  2. The template block is the HTML that Vue renders. Double curly braces show a value.
  3. The style block with scoped only applies to this component. Vue adds a special attribute to the elements, so the class “card” does not leak to other components.
Options API. Vue also has an older style called the Options API, with data, methods and computed as object keys. It still works. New code and this lesson use script setup.

How reactivity works

Vue does not compare the whole page after each change. It knows exactly which code depends on which value.

  1. The reactive function wraps your object in a JavaScript Proxy. A ref does the same job with a getter and a setter on its value property.
  2. When an effect runs and reads a value, Vue records it. An effect is code that Vue runs for you: the render of a component, a computed, or a watcher. This step is called track.
  3. When you write a new value, Vue finds every effect that read it. This step is called trigger.
  4. Vue runs those effects again. The component renders again with the new value.
  5. A plain variable has no Proxy and no setter. Vue cannot see reads or writes on it. That is the bug in the cart badge.
Step 1: run and read (track)Component renderquantity.valuereadsquantitya refVue records:the render depends on quantity.Step 2: write and run again (trigger)quantity.value = 3writesquantityRender againwith the value 3A plain variable has no tracked reads and no triggered writes.
The render reads quantity, so Vue records the link. Later, a write to quantity triggers the render again.
The DOM updates a little later. Vue collects all changes and updates the DOM once, after your synchronous code ends. If you change state and need to read the new DOM right away, await the nextTick function.

ref and reactive

import { reactive, ref, toRefs } from 'vue'

const search = ref('') // any type of value
search.value = 'running shoes' // use .value in script

const filters = reactive({ minPrice: 0, inStock: true }) // objects only
filters.minPrice = 50 // no .value

const { minPrice } = filters // plain number: the link is lost
const { inStock } = toRefs(filters) // a ref linked to filters.inStock
  1. A ref works with any type: a string, a number, an object, an array. In script you read and write it through the value property.
  2. In the template you do not write the value property. Vue unwraps top-level refs for you.
  3. The reactive function works only with objects. You use it like a normal object.
  4. Destructuring a reactive object copies the current values. You get plain numbers and strings, not reactive ones. The toRefs function gives refs that stay linked.
  5. Replacing a reactive object also breaks the link. If you assign a new reactive object to the same variable, the template still watches the old one. With a ref, you just set a new value.
Reactive objectfilters (Proxy)minPrice: 50inStock: trueA copy, no linkconst { minPrice } = filtersA plain number: 50. It sees no changes.Still linkedconst { inStock } = toRefs(filters)A ref that reads filters.inStock.Replacing the whole reactive object breaks the link too.
Destructuring copies the value and breaks the link. The toRefs function gives a ref that still reads from the reactive object.

Because of these traps, the Vue docs suggest ref as the main way to declare state. Many teams use ref everywhere.

computed: values you can calculate

The cart total depends on the items. Do not store it in its own state. Calculate it:

import { computed, ref } from 'vue'

type CartItem = { id: number; name: string; price: number; qty: number }

const items = ref<CartItem[]>([
  { id: 1, name: 'Running shoes', price: 120, qty: 1 },
  { id: 2, name: 'Socks', price: 8, qty: 3 },
])

const total = computed(() =>
  items.value.reduce((sum, item) => sum + item.price * item.qty, 0),
)
  1. A computed is cached. It runs again only when a value it read changes. If you show the total in ten places, it is calculated once.
  2. A normal function in the template runs on every render. For a cheap calculation this is fine. For a big list, use computed.
  3. A computed is read-only by default. Writing to its value gives a warning. You can make it writable with get and set, but you rarely need that.
  4. A computed must have no side effects. No network calls, no changes to other state. It only returns a value.

watch and watchEffect: side effects

Use a watcher when a change must do something outside Vue: call an API, write to localStorage, log an event.

import { reactive, ref, watch, watchEffect } from 'vue'

const search = ref('')
const filters = reactive({ minPrice: 0 })

// A ref as the source
watch(search, (newValue, oldValue) => {
  console.log('search changed', oldValue, '->', newValue)
})

// One property of a reactive object: use a getter function
watch(
  () => filters.minPrice,
  (min) => {
    console.log('min price is now', min)
  },
)

// Runs now, and again when anything it read changes
watchEffect(() => {
  console.log('search:', search.value, 'min:', filters.minPrice)
})
  1. The watch function needs a source: a ref, a reactive object, a getter function, or an array of these. The expression filters.minPrice alone is just a number. Vue cannot watch a number, and it shows a warning in development.
  2. The watch function is lazy. It runs the callback only after a change, and it gives you the new and the old value. Add the immediate option to run it once at the start too.
  3. The watchEffect function runs right away and tracks every reactive value it reads. You do not list the sources.
  4. Deep or not deep. Watching a reactive object directly is deep: a change in any nested property triggers it. A getter that returns an object only triggers when it returns a different object. Add the deep option if you need nested changes.
  5. Do not use a watcher to keep a derived value in sync. That is the job of computed.

Cleanup with onWatcherCleanup

The user types in the search box. Each change sends a request. An old, slow request can finish after a new one and show wrong results. Since Vue 3.5, the onWatcherCleanup function lets you cancel the old work:

import { onWatcherCleanup, ref, watch } from 'vue'

type Product = { id: number; name: string; price: number }

const search = ref('')
const products = ref<Product[]>([])

watch(search, async (q) => {
  const controller = new AbortController()
  onWatcherCleanup(() => controller.abort()) // runs before the next run

  try {
    const res = await fetch(`/api/products?q=${encodeURIComponent(q)}`, {
      signal: controller.signal,
    })
    products.value = await res.json()
  } catch (error) {
    if (!controller.signal.aborted) throw error
  }
})
  1. Vue calls the cleanup function before the watcher runs again, and when the watcher stops.
  2. Call onWatcherCleanup before the first await. Vue only knows which watcher is running during the synchronous part of the callback.
  3. The aborted request rejects with an error. We ignore it, because we cancelled it on purpose.

Template directives

Directives are special attributes that start with v-. These are the ones interviews ask about:

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

type Product = { id: number; name: string; soldOut: boolean }

const products = ref<Product[]>([
  { id: 1, name: 'Running shoes', soldOut: false },
  { id: 2, name: 'Rain jacket', soldOut: true },
])
const isCartOpen = ref(false)

const availableProducts = computed(() =>
  products.value.filter((product) => !product.soldOut),
)
</script>

<template>
  <p v-if="availableProducts.length === 0">No products right now.</p>
  <ul v-else>
    <li v-for="product in availableProducts" :key="product.id">
      {{ product.name }}
    </li>
  </ul>

  <button type="button" @click="isCartOpen = !isCartOpen">Cart</button>
  <aside v-show="isCartOpen" class="mini-cart">Your cart</aside>
</template>
  1. The v-if directive adds or removes the element. When the condition is false, the element and its child components do not exist. Good for things that rarely change.
  2. The v-show directive always renders the element and only toggles the CSS display property. Good for things that toggle often, like a mini cart.
  3. The v-for directive needs a key. Use a stable, unique id, not the index. With the index, Vue can reuse the wrong element after you remove or sort items, and an input can keep the text of another product.
  4. Never put v-if and v-for on the same element. In Vue 3, v-if runs first, so it cannot see the loop variable. Filter the list in a computed, like availableProducts above. Or put the v-for on a template tag around the element.

Props and emits

Data flows one way. The parent passes props down. The child sends events up to ask for a change.

<script setup lang="ts">
const { productId, quantity = 1 } = defineProps<{
  productId: number
  quantity?: number
}>()

const emit = defineEmits<{
  'update:quantity': [value: number]
  remove: [id: number]
}>()
</script>

<template>
  <span>{{ quantity }}</span>
  <button type="button" @click="emit('update:quantity', quantity + 1)">+</button>
  <button type="button" @click="emit('remove', productId)">Remove</button>
</template>
  1. Props are read-only for the child. The parent owns the data. If the child changes a prop, Vue shows a warning in development. Even worse, now two components change the same data and nobody knows who is right.
  2. The child emits an event with the new value. The parent decides and updates its own state. Then the new prop flows down.
  3. Since Vue 3.5, destructured props stay reactive. The compiler turns quantity into a read of the props object for you. You can also give a default value, like quantity = 1 above. Before 3.5, destructuring props lost reactivity.
  4. To watch a destructured prop, use a getter. Write the getter that returns quantity, not quantity alone.
CartPageParent: owns the dataCartItemQuantityChild: only asks for a changeProp (down):quantity="2"Event (up)update:quantity, 3v-model:quantityThe child never changes its own prop.
Props go down from the parent. Events go up from the child. The v-model directive is a short way to write both.

v-model on a component with defineModel

The pair of a prop and an update event is so common that Vue has a short form. Since Vue 3.4, the defineModel macro gives the child a ref that is linked to the parent:

<script setup lang="ts">
const quantity = defineModel<number>('quantity', { required: true })
</script>

<template>
  <button type="button" :disabled="quantity <= 1" @click="quantity--">-</button>
  <span>{{ quantity }}</span>
  <button type="button" @click="quantity++">+</button>
</template>

The parent writes this:

<template>
  <CartItemQuantity v-model:quantity="item.qty" />
</template>
  1. Reading the ref reads the prop from the parent.
  2. Writing the ref emits the update:quantity event. The parent still owns the data and updates it.
  3. Without a name, defineModel uses the default modelValue prop, and the parent writes v-model alone.

Reaching a DOM element with useTemplateRef

Sometimes you need the real element, for example to focus the search box when the page opens:

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

const searchInput = useTemplateRef<HTMLInputElement>('search')

onMounted(() => {
  searchInput.value?.focus()
})
</script>

<template>
  <input ref="search" type="search" placeholder="Search products" />
</template>
  1. The useTemplateRef function (Vue 3.5) takes the same name as the ref attribute in the template.
  2. The value is null before the component is mounted. Use it in onMounted or later.

Slots

A slot lets the parent pass template content into a child. A reusable card can show any title and body:

<template>
  <section class="card">
    <header><slot name="title" /></header>
    <slot />
  </section>
</template>

The parent fills the slots:

<template>
  <BaseCard>
    <template #title>Your cart</template>
    <p>3 items</p>
  </BaseCard>
</template>

A slot can also pass data back to the parent. This is called a scoped slot. A list component can use it to let the parent decide how each product row looks.

Common mistakes

Mistake Result Better way
Destructuring a reactive object The values are plain copies. The screen does not update. Use ref, or toRefs when you destructure.
Forgetting the value property in script You compare or change the ref object, not its value. A ref is always truthy. Read and write the value property in script.
Keeping a derived value in state and syncing it with watch Extra code, a wrong value until the first change, and more room for bugs. Use computed.
Passing state.count to watch Vue gets a number and cannot watch it. Pass a getter function that returns state.count.
v-if and v-for on the same element The v-if cannot see the loop variable. Filter in a computed, or move v-for to a template tag.
Using the index as key Wrong elements are reused after a remove or a sort. Use a stable id.
The child changes a prop A warning, and two owners for the same data. Emit an event, or use defineModel.
Async work in a watcher with no cleanup An old response overwrites a newer one. Cancel the old request with onWatcherCleanup.

Summary in seven lines

  1. Vue records which effects read a reactive value and runs them again when the value changes.
  2. A plain variable, or a value copied out of a reactive object, has no link to the screen.
  3. Use ref for state. In script you need the value property, in the template you do not.
  4. Use computed for anything you can calculate. It is cached and read-only.
  5. Use watch or watchEffect only for side effects. Give watch a ref or a getter, and clean up async work with onWatcherCleanup.
  6. Never mix v-if and v-for on one element, and always give v-for a stable key.
  7. Props go down and events go up. The defineModel macro is a short form of this pair, not a way to share ownership.

Done reading this lesson?Mark it as finished so it shows in your lessons list and report card.