Ref and Reactive in Vue 3

Tram Ho

In Vue 3, there are two Reactivity APIs that are confusing for newbies to use: ref and reactive . In this article, I will show you how to use the above 2 APIs, with some comparisons with Vue 2 for those who have just moved from Vue 2 to Vue 3.

Ref

Simple example when changing a reactive state with Vue 2:

Similar functionality but using ref() in Vue 3:

To better understand how ref() works, you should learn more about Proxy in Javascript .

Some notes about ref():

  • We can save any data to the ref object as well.
  • Ref object is mutable , when you need to change the value, you can change its value property directly. However, when using the ref object in the template, we don’t need the .value because it is automatically unwrapped .

Reactive

In most cases, we just need to use ref() . So what is reactive() used for?

reactive() works similar to ref() but it only accepts objects as arguments, not primitives (number, string, boolean). And we change the value of the reactive object by changing its properties (instead of changing the value property like ref ). The example above is rewritten with reactive() :

In essence, ref() is a function to wrap reactive (inside ref() uses reactive() ), so in most cases we can use most of ref() for synchronization and save a lot of memory. , just pay attention when changing the value of the ref object through the value attribute. You can also use reactive when you want to create a centralized state to avoid creating many variables, for example:

Note that when using reactive we can only pass an object and when updating, we will update the properties of that object, not using direct assignment to the reactive object . For example the following is false:

In line 20 of the above example, the code is wrong because we assign a value to the user variable to a new object. If at the time of declaration using const , it will always report an error, and if using let , the code will be syntactically correct, but when the button is pressed, the interface will not update because the user variable is no longer a reactive object , just a normal object. It can be fixed by updating the properties one by one:

Or use ref() :


Source: https://huydq.dev .

Share the news now

Source : Viblo