Mike Hearn
Mike Hearn

Reputation: 2358

How to use .value on reactive nested objects in Vue 3's Composition API?

I'm wondering where it's correct to use .value when referencing reactive objects if they are nested 2+ levels deep. Do you put .value on the base object and then access sub-keys off that? Or do you put it on the deepest key?

Here is an example:

import { reactive, computed } from 'vue'

const someObj = reactive({
    a: {
        b: {
            c: 1
        }
    }
})

const doubleSomeObj = computed(() => {
    return someObj.value.a.b.c * 2
    // Or... someObj.a.b.c.value * 2
    // Or something else?
})

In the above code, in the computed property doubleSomeObj, it references the nested object someObj.

When referencing the various keys in that nested object someObj, at what level is it correct to put .value?

Upvotes: 1

Views: 4240

Answers (1)

tony19
tony19

Reputation: 138266

.value is only used on refs. The reactive object's subproperties can be used without employing .value, so you could just directly multiply it in your computed prop:

const doubleSomeObj = computed(() => {
    return someObj.a.b.c * 2
})

demo

Upvotes: 3

Related Questions