0 day streak
javascript / intermediate
Snippet

Writable Computed Properties with Getters and Setters

While computed properties are usually read-only, you can create writable ones by providing both a getter and a setter. This is powerful for components that need to bridge the gap between formatted display and raw state data.

snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
const firstName = ref('John');
const lastName = ref('Doe');
const fullName = computed({
get() {
return `${firstName.value} ${lastName.value}`;
},
set(newValue) {
const names = newValue.split(' ');
firstName.value = names[0] || '';
lastName.value = names[names.length - 1] || '';
}
});
vue
Breakdown
1
get() { ... }
Returns the derived value used in the template or other logic.
2
set(newValue) { ... }
Executes logic when the computed property is assigned a new value.
3
firstName.value = names[0]
Updates the underlying reactive state based on the input to the setter.