MrNobody
MrNobody

Reputation: 61

how to deal with Computed and Destructuring assignment in Vue3?

const index = ref('child1')

const children = {
    child1:{ name:'foo' },
  child2:{ name:'bar' },
}

// case 1. I want to destructur and get name variable when index variable is changed to 'child2'. Because computed is not used here, it is not responsive, name variable still is 'foo'
const {name} = children[index.value]

// case 2. After using computed
const child = computed(() => children[index.value])

// Because I used Computed, I got the child object, but I can't deconstruct it
// so I need to use child.name in the template, and i dont want that.
// My puzzle is how to use the name field directly, as in case 1, and responsive as in case 2
// maybe Reactive with toRefs?

I got a playground to explain my confusion

I expect to use the name field directly, as in case 1, and responsive as in case 2

Upvotes: 1

Views: 2534

Answers (2)

Dimava
Dimava

Reputation: 10899

a) deconstruct with toRef or toRefs:

const child = computed(() => children[index.value])
const { name } = toRefs(child)
const name1 = toRef(child, 'name')

b) get name directly

const childName = computed(() => children[index.value].name)

c) use Reactivity Transform (experimental) removed in the vue 3.4

const child = computed(() => children[index.value])
const { name } = $( child ) // name is string

Upvotes: 2

Thomas
Thomas

Reputation: 7108

You could define the computed to be the name directly:

const name = computed(() => children[index.value].name);

Upvotes: 0

Related Questions