Vue3 Ref Function

Posted on  by admin
setup is used to write a combined api, and the internal data and methods need to pass through return before the template can be used.

In the previous vue2, the data returned by data can be directly bound in both directions.

If we bind the data types in setup directly in both directions, we find that variables cannot respond in real time.

Next, let's look at how setup realizes the responsive function of data. The custom attributes in setup do not have responsive ability, so ref is introduced. The bottom layer of ref wraps the attribute wrapping value into an proxy through proxy, and the inside of proxy is an object, which makes the basic type of data have responsive ability and must be introduced before use.

Example 1: ref uses . At this time, mood can be edited arbitrarily in setup template, which can ensure real-time response.

Instance adds value to modify the value of mood because ref works as follows: .


So reactive is introduced. reactive wraps reference type data into proxy through underlying wrapping, as follows: .

When referencing, just use me. Example 2: reactive uses .

The responsive function of data in vue2 can be fully realized through setup + ref + reactive, so setup can completely replace data.

setup + ref + reactive implements a data-responsive expression, which cannot be deconstructed using ES6 and eliminates the response characteristic.

Therefore, toRefs deconstruction is needed. When using it, it needs to be introduced first.


3. Application of toRefs and toRef