Computed properties with getter and setter let you create values that update automatically and can also change other data when you set them.
Computed with getter and setter in 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.
computed: {
fullName: {
get() {
return this.firstName + ' ' + this.lastName;
},
set(value) {
const parts = value.split(' ');
this.firstName = parts[0];
this.lastName = parts.slice(1).join(' ') || '';
}
}
}computed: {
reversedMessage: {
get() {
return this.message.split('').reverse().join('');
},
set(value) {
this.message = value.split('').reverse().join('');
}
}
}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.
<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>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.
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.
Practice
What is the main purpose of a computed property with both get and set in Vue?
Solution
Step 1: Understand computed properties
Computed properties in Vue are reactive and can automatically update when dependencies change.Step 2: Role of getter and setter
Using bothgetandsetallows reading the value and updating related data reactively.Final Answer:
To create a reactive property that can both read and update data -> Option AQuick Check:
Computed with get/set = reactive read and write [OK]
- Thinking computed properties are static
- Confusing computed with methods
- Believing set is optional for writing data
Which of the following is the correct syntax to define a computed property with a getter and setter in Vue 3 using <script setup>?
const fullName = computed({
get() {
return this.firstName + ' ' + this.lastName
},
set(value) {
const names = value.split(' ')
this.firstName = names[0]
this.lastName = names[1]
}
})Solution
Step 1: Check computed property syntax
Vue 3 allows computed properties with an object containinggetandsetmethods.Step 2: Validate the example code
The code correctly definesgetandsetas functions inside an object passed tocomputed().Final Answer:
Correct as is -> Option BQuick Check:
Object with get/set inside computed = correct syntax [OK]
- Using arrow functions that break 'this' context
- Omitting commas between get and set
- Trying to define computed as a single function
Given this Vue 3 <script setup> code, what will be the console output after fullName.value = 'Jane Doe'?
import { ref, computed } from 'vue'
const firstName = ref('John')
const lastName = ref('Smith')
const fullName = computed({
get() {
return firstName.value + ' ' + lastName.value
},
set(value) {
const names = value.split(' ')
firstName.value = names[0]
lastName.value = names[1]
}
})
fullName.value = 'Jane Doe'
console.log(firstName.value, lastName.value)Solution
Step 1: Understand the setter logic
SettingfullName.valuesplits the string into ['Jane', 'Doe'] and assigns tofirstName.valueandlastName.value.Step 2: Check console.log output
After assignment,firstName.valueis 'Jane' andlastName.valueis 'Doe', so console logs 'Jane Doe'.Final Answer:
'Jane' 'Doe' -> Option CQuick Check:
Setter splits and assigns names = 'Jane' 'Doe' [OK]
- Expecting full string in firstName
- Thinking computed properties are read-only
- Confusing ref.value and computed.value
What is wrong with this computed property definition in Vue 3?
const fullName = computed({
get: () => {
return firstName.value + ' ' + lastName.value
},
set: (value) => {
const names = value.split(' ')
firstName.value = names[0]
lastName.value = names[1]
}
})Solution
Step 1: Analyze arrow function usage
Arrow functions do not bind their ownthis, which can break reactivity when accessing reactive refs inside get/set.Step 2: Understand Vue reactivity context
Using normal function syntax ensures correct reactivity and access to reactive data.Final Answer:
Arrow functions break the reactivity context for get and set -> Option AQuick Check:
Use normal functions, not arrow, for computed get/set [OK]
- Using arrow functions for get/set
- Thinking commas are missing
- Believing set is not allowed
You want to create a computed property fullName that updates firstName and lastName refs, but also trims extra spaces and handles single names gracefully. Which computed property definition is best?
const fullName = computed({
get() {
return `${firstName.value.trim()} ${lastName.value.trim()}`.trim()
},
set(value) {
const names = value.trim().split(/\s+/)
firstName.value = names[0] || ''
lastName.value = names.slice(1).join(' ') || ''
}
})Solution
Step 1: Check trimming in getter
The getter trims both first and last names and then trims the combined string to avoid extra spaces.Step 2: Analyze setter logic
The setter trims input, splits by spaces, assigns first word to firstName, and joins the rest for lastName, handling single names gracefully.Final Answer:
This handles trimming and single names correctly -> Option DQuick Check:
Trim and split with fallback = robust computed set/get [OK]
- Not trimming input causing extra spaces
- Failing on single-word names
- Using split without regex for multiple spaces
Ready to prove it?
Pass the test and this pattern moves unknown
