In Vue.js 3, why do I have to use the value property on ref, but not on reactive?

Viewed 1152

Basically, the title already says it all: In Vue.js 3, why do I have to use the value property on ref, but not on reactive?

I understand that ref is for simple values, such as booleans, numbers, …, and that reactive is for complex values such as objects and arrays. What I do not get is:

  • Why do I need to specify value when I want to access a ref's value, but not if I use reactive? Isn't this an inconsistency in the API, or is there an actual technical reason why it has to be this way?
  • Why am I not able to use one for both? In other words: Is there a technical reason why there isn't a single function which decides, depending on the type of the given value, how to wrap this internally?

I assume that I am missing something and it's not that easy. Can anyone help?

1 Answers

Yes, Ref and Reactive are both reactive variable wrappers.

const refVar = ref(true)
const reactiveVar = reactive({ haha: 'LoL' })

Here both refVar and reactiveVar are just wrapper variables to keep reactivity for their values inside. And as you said, difference between ref and reactive is that ref is for single variable and reactive is for dictionary-structured variable.

ref looks after the changes in its value property and once changed it emits reactive event, so that observers can be updated automatically. But reactive looks after all its properties.

If you use only reactive, it would be very uncomfortable to keep reactivity for single variables.

const refSingle = reactive({ value: 'I wanna be used with Ref' })

And you should call refSingle.value all the time on template side.

If you use only ref, it would be very difficult to keep reactivity for dict-typed variables.

const reactiveDict = ref({
  type: 'dictionary',
  purpose: 'reactive'
})

In this case, if you use it in script, you should use value property every time.

reactiveDict.value = {
  ...reactiveDict.value,
  purpose: 'ref'
}

In this case, you can use reactive rather than ref.

Related