Search⌘ K

Computed Properties and Watchers

Explore how to use computed properties to efficiently recalculate reactive values and watchers to perform side effects when data changes. Understand how these features improve code organization, performance, and reactivity within Nuxt 3's Composition API.

We'll cover the following...

Both computed properties and watchers are also available using the Composition API.

Computed properties

Computed properties are used to recalculate a value each time the reactive data changes. An example of a computed property could be a shopping basket total. Each time a new product is added to the basket, the total will be recalculated.

We’ll start with computed properties by first looking at the problem. Let’s look at the example component below:

Javascript (babel-node)
<script setup>
let state = reactive({
user: { name: "Bob", location: "UK", orders: 1 },
darkMode: false,
});
</script>
<template>
<p>
{{
state.user.orders === 0 ? "Get 5% off your first order" : "Welcome back"
}}
</p>
</template>

If a user has placed an order previously, they see a “Welcome back” message, if not, they receive a discount. Here is a working example that can be improved. Template expressions using ...