In the vue documentation - Writable Computed, this example below is given.
<script setup>
import { ref, computed } from 'vue'
const firstName = ref('John')
const lastName = ref('Doe')
const fullName = computed({
// getter
get() {
return firstName.value ' ' lastName.value
},
// setter
set(newValue) {
// Note: we are using destructuring assignment syntax here.
[firstName.value, lastName.value] = newValue.split(' ')
}
})
</script>
and is used like this
fullName.value = 'John Doe'
The computed property is updated with .value otherwise it doesn't work. Is it because we use reactive (ref()) object in setter and getter?
CodePudding user response:
The answer is here :
computed()
Takes a getter function and returns a readonly reactiveref
object for the returned value from the getter. It can also take an object with get and set functions to create a writableref
object.
The can be well explained with Typescript definition :
// read-only
function computed<T>(
getter: () => T,
// see "Computed Debugging" link below
debuggerOptions?: DebuggerOptions
): Readonly<Ref<Readonly<T>>> //<---- return a readonly ref
// writable
function computed<T>(
options: {
get: () => T
set: (value: T) => void
},
debuggerOptions?: DebuggerOptions
): Ref<T> //<-------- returns a ref