Performance: Computed with getter and setter
This affects how reactive data updates trigger DOM updates and re-renders in Vue components.
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(' ') || ''; } });
const fullName = computed(() => firstName.value + ' ' + lastName.value); // Updating fullName directly is not possible, so manual watchers or methods are used to sync changes
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Computed with getter only and manual sync | Multiple reactive triggers | Multiple reflows per update | Higher paint cost due to redundant renders | [X] Bad |
| Computed with getter and setter | Single reactive trigger per update | Single reflow per update | Lower paint cost due to optimized renders | [OK] Good |
What is the main purpose of a computed property with both get and set in Vue?
get and set allows reading the value and updating related data reactively.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]
}
})get and set methods.get and set as functions inside an object passed to computed().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)fullName.value splits the string into ['Jane', 'Doe'] and assigns to firstName.value and lastName.value.firstName.value is 'Jane' and lastName.value is 'Doe', so console logs 'Jane Doe'.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]
}
})this, which can break reactivity when accessing reactive refs inside get/set.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(' ') || ''
}
})Pass the test and this pattern moves unknown