javascript / intermediate
Snippet
Writable Computed Properties
By default, computed properties are getter-only. However, you can provide an object with both 'get' and 'set' to create a writable computed property, which is useful for two-way data binding with logic.
snippet.js
1
2
3
4
5
6
7
8
9
10
11
12
13
import { ref, computed } from 'vue';const firstName = ref('Jane');const lastName = ref('Doe');const fullName = computed({get() {return `${firstName.value} ${lastName.value}`;},set(newValue) {[firstName.value, lastName.value] = newValue.split(' ');}});
vue
Breakdown
1
get() { ... }
Defines how the value is calculated from other reactive sources.
2
set(newValue) { ... }
Allows updating the underlying state when the computed property is assigned a new value.