...

/

Computed Properties and Watchers

Computed Properties and Watchers

Learn about the computed properties and watchers to enable the project to react to changes.

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:

Press + to interact
<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 ...