Home > Blockchain >  How to keep vue reactivity when getting a string from another reactive object
How to keep vue reactivity when getting a string from another reactive object

Time:01-26

I know that the title maybe a bit complex to understand (I didn't know how to put it simply), so here's a minimal example. Imagine I got a reactive object ObjectA and I try to copy one if its property:

const objectA = reactive({
    name: "test"
})

const objectB_01 = reactive({
    name: a.name
}) // lose reactivity

const objectB_02 = reactive({
    name: ref(a.name)
}) // lose reactivity

const objectB_03 = reactive({
    get name() { return a.name }
}) // keep reactivity

When I have a template that look like this:

<template>
    <div>{{ objectA.name }}</div>
</template>

Then, the name is reactive (meaning, if I change it somewhere, the template gets updated instantly).

But it does not work objectB_01.name, nor objectB_02.name. It only works with objectB_03.name, but If find it a bit of a hacky solution.

My question is: is there a proper way of doing that? I mean, using a get operator does works but is really not that clean, I find...

CodePudding user response:

For example reactive api

reactive will unwrap all the deep refs, while maintaining the ref reactivity

const count = ref(1)
const obj = reactive({ count })

// ref will be unwrapped
console.log(obj.count === count.value) // true

// it will update `obj.count`
count.value  
console.log(count.value) // 2
console.log(obj.count) // 2

// it will also update `count` ref
obj.count  
console.log(obj.count) // 3
console.log(count.value) // 3

You should look at more this; https://v3.vuejs.org/api/basic-reactivity.html#reactive

CodePudding user response:

If you want the value to be reactive across both objectA and objectB, you need a single source of the value, so getters and setters are the only way.

const objectB_03 = reactive({
    get name() { return a.name },
    set name(value) { a.name = value }
}) // keep reactivity

In fact, Vue2 data does just that, ref How Changes Are Tracked

When you pass a plain JavaScript object to a Vue instance as its data option, Vue will walk through all of its properties and convert them to getter/setters

  •  Tags:  
  • Related