Computed properties with getter and setter let you create values that update automatically and can also change other data when you set them.
0
0
Computed with getter and setter in Vue
Introduction
You want to show a value based on other data but also let users change it.
You need to format or combine data for display and update the original data when edited.
You want to keep your template simple by using computed properties instead of methods.
You want to react to changes in a value and update related data automatically.
Syntax
Vue
computed: {
propertyName: {
get() {
// return a value based on other data
},
set(newValue) {
// update other data based on newValue
}
}
}The get function returns the computed value.
The set function runs when you assign a new value to the computed property.
Examples
This example combines first and last names and updates them when fullName changes.
Vue
computed: {
fullName: {
get() {
return this.firstName + ' ' + this.lastName;
},
set(value) {
const parts = value.split(' ');
this.firstName = parts[0];
this.lastName = parts.slice(1).join(' ') || '';
}
}
}This example reverses a message string and updates the original message when reversedMessage changes.
Vue
computed: {
reversedMessage: {
get() {
return this.message.split('').reverse().join('');
},
set(value) {
this.message = value.split('').reverse().join('');
}
}
}Sample Program
This Vue component shows an input bound to a computed property with getter and setter. Changing the input updates first and last names separately. The paragraphs show the current first and last names.
Vue
<template>
<div>
<input v-model="fullName" aria-label="Full name input" />
<p>Your first name is: {{ firstName }}</p>
<p>Your last name is: {{ lastName }}</p>
</div>
</template>
<script setup>
import { ref, computed } from 'vue'
const firstName = ref('John')
const lastName = ref('Doe')
const fullName = computed({
get() {
return `${firstName.value} ${lastName.value}`
},
set(value) {
const parts = value.split(' ')
firstName.value = parts[0] || ''
lastName.value = parts.slice(1).join(' ') || ''
}
})
</script>OutputSuccess
Important Notes
Computed properties with setters let you create two-way bindings easily.
Always handle cases where the input might not split cleanly to avoid errors.
Use v-model on computed properties with setters for smooth user input.
Summary
Computed properties can have both get and set to read and write values.
This helps keep your data and UI in sync with less code.
Use them to create smart, reactive properties that update other data when changed.