Computed properties are great way to cache data. These cache data only change when the reactive properties it depends on changes. Let’s have a look at how we can define a computed property in Vue.js. In the example below, I’m letting the user enter a name through a text field. Whenever they type something, the computed property will look for the updated state and it’ll convert the input into uppercase. We then display the uppercased version of the input state in a new line. The reset button will reset it’s value to empty string.
<template>
<div>
<input v-model="inputData.name" type="text" placeholder="Enter name" />
<h3 v-if="capitalizedName">
Capitalized: {{capitalizedName}}
</h3>
<div v-if="capitalizedName" class="buttons-container">
<button @click="clearName">Reset</button>
</div>
</div>
</template>
<script setup>
import { reactive, computed } from "vue";
const inputData = reactive({
name: ''
})
const capitalizedName = computed(() => {
return inputData.name.toUpperCase()
})
const clearName = () => (inputData.name = "");
</script>
Code language: HTML, XML (xml)
In the above code, we’ve declared a computed property named capitalizedName. We’ve then calculated it’s value through the reactive state inputData.name.
We’ve returned it’s the uppercased value of inputDate.name with inputData.name.toUpperCase(). We can then access this value directly using capitalizedName property.