Vue 3 reactive()

Vue 3 reactive() DEFAULT

  You block advertising 😢
Would you like to buy me a ☕️ instead?

One of the first questions that arise when starting with the new Vue Composition API is or ? The initial instinct is to use for primitives (Boolean, String,…) and for objects. But there is more to it.

When to Use and When to Use ?

Let’s start with the basics: you must use to create a reactive primitive value.

, on the other hand, can only be used for creating reactive objects. You can use it as a replacement for the old option in standard Option API-based Vue components, for example.

But you can also use for that. In the following example, we use to create a reactive object.

There are two notable differences when using instead of for objects. The first one is more of a downside, but I consider the second one a significant advantage.


Screenshots of three premium Vue.js templates.

Constantly having to use when working with refs is a bummer. But at least it makes it very clear that you’re working with reactive data.

One possible workaround, especially when dealing with data that might or might not be a ref, is to use .

Is Mixing and a Good Idea?

Because I think sometimes having to use and sometimes not is confusing, I tend not to use at all.

Yes, always having to deal with even if I could avoid it sometimes by using is annoying. But the magic word here is sometimes. can be used for every occasion, can’t. I much prefer consistency over a minor annoyance.

Sours: https://markus.oberlehner.net/blog/vue-3-composition-api-ref-vs-reactive/

On-demand Reactivity in Vue 3

Apart from admirable performance improvements, the recently released Vue 3 also brought several new features. Arguably the most important introduction is the Composition API. In the first part of this article, we recap the standard motivation for a new API: better code organization and reuse. In the second part, we will focus on less-discussed aspects of using the new API, such as implementing reactivity-based features that were inexpressible in Vue 2’s reactivity system.

We will refer to this as on-demand reactivity. After introducing the relevant new features, we will build a simple spreadsheet application to demonstrate the new expressiveness of Vue’s reactivity system. At the very end, we will discuss what real-world use this improvement on-demand reactivity might have.

What’s New in Vue 3 and Why it Matters

Vue 3 is a major rewrite of Vue 2, introducing a plethora of improvements while retaining backward compatibility with the old API almost in its entirety.

One of the most significant new features in Vue 3 is the Composition API. Its introduction sparked much controversy when it was first discussed publicly. In case you are not already familiar with the new API, we will first describe the motivation behind it.

The usual unit of code organization is a JavaScript object whose keys represent various possible types of a piece of a component. Thus the object might have one section for reactive data (), another section for computed properties (), one more for component methods (), etc.

Under this paradigm, a component can have multiple unrelated or loosely related functionalities whose inner workings are distributed among the aforementioned component sections. For example, we might have a component for uploading files that implements two essentially separate functionalities: file management and a system that controls the upload status animation.

The portion might contain something like the following:

There are benefits to this traditional approach to code organization, mainly in the developer not having to worry about where to write a new piece of code. If we’re adding a reactive variable, we insert it in the section. If we’re looking for an existing variable, we know it must be in the section.

This traditional approach of splitting the functionality’s implementation into sections (, , etc.) is not suitable in all situations.

The following exceptions are cited often:

  1. Dealing with a component with a large number of functionalities. If we want to upgrade our animation code with the ability to delay the start of the animation, for example, we will have to scroll/jump between all the relevant sections of the component in a code editor. In the case of our file-uploading component, the component itself is small and the number of functionalities it implements is small, too. Thus, in this case, jumping between the sections is not really a problem. This issue of code fragmentation becomes relevant when we deal with large components.
  2. Another situation where the traditional approach is lacking is code reuse. Often we need to make a specific combination of reactive data, computed properties, methods, etc., available in more than one component.

Vue 2 (and the backward-compatible Vue 3) offer a solution to most of the code organization and reuse issues: mixins.

Pros and Cons of Mixins in Vue 3

Mixins allow the functionalities of a component to be extracted in a separate unit of code. Each functionality is put in a separate mixin and every component can use one or more mixins. Pieces defined in a mixin can be used in a component as if they were defined in the component itself. The mixins are a bit like classes in object-oriented languages in that they collect the code related to a given functionality. Like classes, mixins can be inherited (used) in other units of code.

However, reasoning with mixins is harder since, unlike classes, mixins need not be designed with encapsulation in mind. Mixins are allowed to be collections of loosely bound pieces of code without a well-defined interface to the outer world. Using more than one mixin at a time in the same component might result in a component that is difficult to comprehend and use.

Most object-oriented languages (e.g., C# and Java) discourage or even disallow multiple inheritance despite the fact that the object-oriented programming paradigm has the tools to deal with such complexity. (Some languages do allow multiple inheritance, such as C++, but composition is still preferred over inheritance.)

A more practical issue that may occur when using mixins in Vue is name collision, which occurs when using two or more mixins declaring common names. It should be noted here that if Vue’s default strategy for dealing with name collisions is not ideal in a given situation, the strategy can be adjusted by the developer.This comes at the cost of introducing more complexity.

Another issue is that mixins do not offer something akin to a class constructor. This is a problem because often we need functionality that is very similar, but not exactly the same, to be present in different components. This can be circumvented in some simple cases with the use of mixin factories.

Therefore, mixins are not the ideal solution for code organization and reuse, and the larger the project, the more serious their issues become. Vue 3 introduces a new way of solving the same issues concerning code organization and reuse.

Composition API: Vue 3’s Answer to Code Organisation and Reuse

The Composition API allows us (but does not require us) to completely decouple the pieces of a component. Every piece of code—a variable, a computed property, a watch, etc.—can be defined independently.

For example, instead of having an object that contains a section that contains a key with the (default) value “playing,” we can now write (anywhere in our JavaScript code):

The effect is almost the same as declaring this variable in the section of some component. The only essential difference is that we need to make the defined outside of the component available in the component where we intend to use it. We do this by importing its module to the place where the component is defined and return the from the section of a component. We’ll skip this procedure for now and just focus on the new API for a moment. Reactivity in Vue 3 doesn’t require a component; it’s actually a self-contained system.

We can use the variable in any scope that we import this variable to. After constructing a , we get and set its actual value using , for example:

We need the ‘.value’ suffix since the assignment operator would otherwise assign the (non-reactive) value “paused” to the variable . Reactivity in JavaScript (both when it is implemented through the as in Vue 2, and when it’s based on a as in Vue 3) requires an object whose keys we can work with reactively.

Note that this was the case in Vue 2, as well; there, we had a component as a prefix to any reactive data member (). Unless and until the JavaScript language standard introduces the ability to overload the assignment operator, reactive expressions will require an object and a key (e.g., and as above) to appear on the left-hand side of any assignment operation where we wish to preserve reactivity.

In templates, we can omit since Vue has to preprocess the template code and can automatically detect references:

In theory, the Vue compiler could preprocess the portion of a Single File Component (SFC) in a similar way, too, inserting where needed. However, the use of would then differ based on whether we are using SFCs or not, so perhaps such a feature is not even desirable.

Sometimes, we have an entity (for example, be a Javascript object or an array) that we never intend to replace with a completely different instance. Instead, we might only be interested in modifying its keyed fields. There is a shorthand in this case: using instead of allows us to dispense with the :

Decoupled reactivity with and is not a completely new feature of Vue 3. It was partly introduced in Vue 2.6, where such decoupled instances of reactive data were called “observables.” For the most part, one can replace with . One of the differences is that accessing and mutating the object passed to directly is reactive, while the new API returns a proxy object, so mutating the original object will not have reactive effects.

Comparison: Options API vs. Composition API.

What is completely new in Vue 3 is that other reactive pieces of a component can now be defined independently too, in addition to reactive data. Computed properties are implemented in an expected way:

Similarly one can implement various types of watches, lifecycle methods, and dependency injection. For the sake of brevity, we won’t cover those here.

Suppose we use the standard SFC approach to Vue development. We might even be using the traditional API, with separate sections for data, computed properties, etc. How do we integrate the Composition API’s small bits of reactivity with SFCs? Vue 3 introduces another section just for this: . The new section can be thought of as a new lifecycle method (which executes before any other hook—in particular, before ).

Here is an example of a complete component that integrates the traditional approach with the Composition API:

Things to take away from this example:

  • All the Composition API code is now in . You might want to create a separate file for each functionality, import this file in an SFC, and return the desired bits of reactivity from (to make them available to the remainder of the component).
  • You can mix the new and the traditional approach in the same file. Notice that , even though it’s a reference, does not require when referred to in the template code or in traditional sections of a component such as .
  • Last but not least, notice we have two root DOM nodes in our template; the ability to have multiple root nodes is another new feature of Vue 3.

Reactivity is More Expressive in Vue 3

In the first part of this article, we touched upon the standard motivation for the Composition API, which is improved code organization and reuse. Indeed, the new API’s main selling point is not its power, but the organizational convenience that it brings: the ability to structure the code more clearly. It might seem like that is all—that the Composition API enables a way of implementing components that avoids the limitations of the already existing solutions, such as mixins.

However, there is more to the new API. The Composition API actually enables not just better organized but more powerful reactive systems. The key ingredient is the ability to dynamically add reactivity to the application. Previously, one had to define all the data, all the computed properties, etc. before loading a component. Why would adding reactive objects at a later stage be useful? In what remains we take a look at a more complex example: spreadsheets.

Creating a Spreadsheet in Vue 2

Spreadsheet tools such as Microsoft Excel, LibreOffice Calc, and Google Sheets all have some sort of a reactivity system. These tools present a user with a table, with columns indexed by A–Z, AA–ZZ, AAA–ZZZ, etc., and rows indexed numerically.

Each cell may contain a plain value or a formula. A cell with a formula is essentially a computed property, which may depend on values or other computed properties. With standard spreadsheets (and unlike the reactivity system in Vue), these computed properties are even allowed to depend on themselves! Such self-reference is useful in some scenarios where the desired value is obtained by iterative approximation.

Once a cell’s content changes, all the cells that depend on the cell in question will trigger an update. If further changes occur, further updates might be scheduled.

If we were to build a spreadsheet application with Vue, it would be natural to ask if we can put Vue’s own reactivity system to use and make Vue the engine of a spreadsheet app. For each cell, we could remember its raw editable value, as well as the corresponding computed value. Computed values would reflect the raw value if it’s a plain value, and otherwise, the computed values are the result of the expression (formula) that is written instead of a plain value.

With Vue 2, a way to implement a spreadsheet is to have a two-dimensional array of strings, and a (computed) two-dimensional array of cell values.

If the number of cells is small and fixed before the appropriate Vue component loads, we could have one raw and one computed value for every cell of the table in our component definition. Aside from the aesthetic monstrousness that such an implementation would cause, a table with a fixed number of cells at compile-time probably doesn’t count as a spreadsheet.

There are problems with the two-dimensional array , too. A computed property is always a function whose evaluation, in this case, depends on itself (calculating the value of a cell will, in general, require some other values to already be computed). Even if Vue allowed self-referential computed properties, updating a single cell would cause all cells to be recomputed (regardless of whether there are dependencies or not). This would be extremely inefficient. Thus, we might end up using reactivity to detect changes in the raw data with Vue 2, but everything else reactivity-wise would have to be implemented from scratch.

Modeling Computed Values in Vue 3

With Vue 3, we can introduce a new computed property for every cell. If the table grows, new computed properties are introduced.

Suppose we have cells and , and we wish for to display the square of whose value is the number 5. A sketch of this situation:

Suppose we stay in this simple scenario for a moment. There is an issue here; what if we wish to change so that it contains the number 6? Suppose we write this:

This didn’t merely change the value 5 to 6 in . The variable has a completely different identity now: the computed property that resolves to the number 6. However, the variable still reacts to changes of the old identity of the variable . So, shouldn’t refer to directly, but rather to some special object that will always be available in the context, and will tell us what is at the moment. In other words, we need a level of indirection before accessing , something like a pointer. There are no pointers as first-class entities in Javascript, but it’s easy to simulate one. If we wish to have a pointing to a , we can create an object . Redirecting the pointer amounts to assigning to , and dereferencing (accessing the pointed-to value) amounts to retrieving the value of . In our case we proceed as follows:

Now we can substitute 5 with 6.

On Vue’s Discord server, the user redblobgames suggested another interesting approach: instead of using computed values, use references that wrap regular functions. This way, one can similarly swap the function without changing the identity of the reference itself.

Our spreadsheet implementation will have cells referred to by keys of some two-dimensional array. This array can provide the level of indirection we require. Thus in our case, we won’t require any additional pointer simulation. We could even have one array that does not distinguish between raw and computed values. Everything can be a computed value:

However, we really want to distinguish raw and computed values since we want to be able to bind the raw value to an HTML input element. Furthermore, if we have a separate array for raw values, we never have to change the definitions of computed properties; they will update automatically based on the raw data.

Implementing the Spreadsheet

Let’s start with some basic definitions, which are for the most part self-explanatory.

The plan is for every to be computed as follows. If doesn’t start with , return . Otherwise, parse the formula, compile it to JavaScript, evaluate the compiled code, and return the value. To keep things short, we’ll cheat a bit with parsing formulas and we won’t do some obvious optimizations here, such as a compilation cache.

We will assume that users can enter any valid JavaScript expression as a formula. We can replace references to cell names that appear in user’s expressions, such as A1, B5, etc., with the reference to the actual cell value (computed). The following function does this job, assuming that strings resembling cell names really always identify cells (and are not a part of some unrelated JavaScript expression). For simplicity, we will assume column indices consist of a single letter.

Using the function, we can get pure JavaScript expressions out of expressions written in our little “extension” of JavaScript with cell references.

The next step is to generate computed properties for every cell. This procedure will occur once in the lifetime of every cell. We can make a factory that will return the desired computed properties:

If we put all of the code above in the method, we need to return .

Below, we present the complete component, together with a basic user interface.

The code is available on GitHub, and you can also check out the live demo.

What About Real-world Use?

We saw how the decoupled reactivity system of Vue 3 enables not only cleaner code but allows more complex reactive systems based on the Vue’s new reactivity mechanism. Roughly seven years have passed since Vue was introduced, and the rise in expressiveness was clearly not highly sought after.

The spreadsheet example is a straightforward demonstration of what Vue is capable of now, and you can also check out the live demo.

But as a real-word example, it is somewhat niche. In what sort of situations might the new system come in handy? The most obvious use-case for on-demand reactivity might be in performance gains for complex applications.

Vue 2 vs Vue 3 funnel comparison.

In front-end applications that work with a large amount of data, the overhead of using poorly thought-through reactivity might have a negative impact on performance. Suppose we have a business dashboard application that produces interactive reports of the company’s business activity. The user can select a time range and add or remove performance indicators in the report. Some indicators may display values that depend on other indicators.

One way to implement report generation is through a monolithic structure. When the user changes an input parameter in the interface, a single computed property, e.g., , gets updated. The computation of this computed property happens according to a hardcoded plan: first, calculate all the independent performance indicators, then those that depend only on these independent indicators, etc.

A better implementation will decouple bits of the report and compute them independently. There are some benefits to this:

  • The developer does not have to hardcode an execution plan, which is tedious and error-prone. Vue’s reactivity system will automatically detect dependencies.
  • Depending on the amount of data involved, we might get substantial performance gains since we are only updating the report data that logically depended on the modified input parameters.

If all performance indicators that may be a part of the final report are known before the Vue component gets loaded, we may be able to implement the proposed decoupling even with Vue 2. Otherwise, if the backend is the single source of truth (which is usually the case with data-driven applications), or if there are external data providers, we can generate on-demand computed properties for every piece of a report.

Thanks to Vue 3, this is now not only possible but easy to do.

Understanding the basics

Vue 3, codenamed "One Piece," is the latest release.

Vue 3 is officially stable. However, while writing the code examples presented in this article, I encountered and reported some minor issues.

Yes, in the sense that it does not require substantial changes to your code. However, many apps will require some minor changes.

Vue was first made public in February 2014. Vue 1.0 was released in October 2015, and the latest version (Vue 3.0) was released in September 2020.

Sours: https://www.toptal.com/vue-js/on-demand-reactivity-vue-3
  1. Char broil egg grill parts
  2. Dirt bike chain and sprocket
  3. Custom logo stamp for wood

Reactivity in Vue 3

Dec 11, 2020

Vue 3 has a new reactivity system based on ES6 proxies. The new reactivity system overlaps with the much-debated Composition API because the Composition API lets you use Vue's reactivity system without using Vue components at all. Some people have even talked about using Vue as a backend framework. Here's how it works.

Using

Vue has a global function that creates a reactive wrapper around a JavaScript primitive. For example, here's how you can create a "reactive" counter object.

What's interesting about this ? Using Vue's global function, you can watch for updates to .

Vue is smart enough to understand values returned from , so you can define reactive state without defining a property. For example, even though the component doesn't have a property, it still reacts to updates to the value of because is a ref.

Using

Vue 3 also introduces a function that behaves like , but for objects. Remember that generally should only be used on primitive values: numbers, strings, booleans, BigInts, and symbols.

The function adds reactivity to an object's properties. Call on an object, and you get back a proxied object that you can use with . For example, because is reactive in the below example, will print out the character's name every time it changes.

The biggest improvement with versus Vue 2's property is that can listen for when you create new properties, not just access existing ones. In the below example, is smart enough to pick up when you create a new property on .

One gotcha with : it debounces changes that happen on the same tick of the event loop. The below code will print "61" and "62", it will not print "59" or "60" because those changes happen synchronously before "61".

If you need to return an object property from , you should use . For example, if instead of having a simple , you have an with a property that you want to increment, you should wrap the object in .


Vue School has some of our favorite Vue video courses. Their Vue.js Master Class walks you through building a real world application, and does a great job of teaching you how to integrate Vue with Firebase. Check it out!


More Vue Tutorials

Sours: https://masteringjs.io/tutorials/vue/reactivity
Ref vs Reactive - Vue 3 Composition API - Vue.js 3 Tutorial

Reactivity systems are one of the key parts of modern front-end frameworks. They’re the magic wand which makes apps highly interactive, dynamic, and responsive. Understanding what a reactivity system is and how it can be applied in practice is a crucial skill for every web developer.

A reactivity system is a mechanism which automatically keeps in sync a data source (model) with a data representation (view) layer. Every time the model changes, the view is re-rendered to reflect the changes.

Let’s take a simple Markdown editor as an example. It usually has two panes: one for writing the Markdown code (which modifies the underlying model), and one for previewing the compiled HTML (which shows the updated view). When you write something in the writing pane, it’s immediately and automatically previewed in the previewing pane. Of course, this is just a simple example. Often things are far more complex.

In many cases, the data we want to display depends on some other data. In such a scenario, the dependencies are tracked and the data is updated accordingly. For example, let’s say we have a property, which depends on and properties. When any of its dependencies are modified, the property is automatically re-evaluated and the result is displayed in the view.

Now that we’ve established what reactivity is, it’s time to learn how the new Vue 3 reactivity works, and how we can use it in practice. But before we do this, we’ll take a quick look at the old Vue 2 reactivity and its caveats.

A Brief Exploration of Vue 2 Reactivity

Reactivity in Vue 2 is more or less “hidden”. Whatever we put in the object, Vue makes it reactive implicitly. On the one hand, this makes the developer’s job easier, but on the other hand it leads to less flexibility.

Behind the scenes, Vue 2 uses the ES5 Object.defineProperty() to convert all of the object’s properties into getters and setters. For each component instance, Vue creates a dependencies watcher instance. Any properties collected/tracked as dependencies during the component’s render are recorded by the watcher. Later on, when a dependency’s setter is triggered, the watcher is notified and the component re-renders and updates the view. This is basically how all the magic works. Unfortunately, there are some caveats.

Change Detection Caveats

Because of the limitations of , there are some data changes that Vue can’t detect. These include:

  • adding/removing a property to/from an object (such as )
  • setting array items by index (such as )
  • modifying the length of an array (such as )

Fortunately, to deal with these limitations Vue provides us with the Vue.set API method, which adds a property to a reactive object, ensuring the new property is also reactive and thus triggers view updates.

Let’s explore the above cases in the following example:

Here’s a CodePen example.

In the above example, we can see that none of the three methods is working. We can’t add a new property to the object. We can’t edit an item from the array by using its index. And we can’t modify the length of the array.

Of course, there are workarounds for these cases and we’ll explore them in the next example:

Here’s a CodePen example.

In this example, we use the API method to add the new property to the object and to select/modify a particular item from the activities array. In the last case, we just use the JavaScript built-in array method.

As we can see, this works, but it’s a bit hacky and leads to inconsistency in the codebase. Fortunately, in Vue 3 this has been resolved. Let’s see the magic in action, in the following example:

Here’s a CodePen example.

In this example, which uses Vue 3, we revert to the built-in JavaScript functionality, used in the first example, and now all methods work like a charm.

In Vue 2.6, a Vue.observable() API method was introduced. It exposes, to some extent, the reactivity system allowing developers to make objects reactive explicitly. Actually, this is the exact same method Vue uses internally to wrap the object and is useful for creating a minimal, cross-component state store for simple scenarios. But despite its usefulness, this single method can’t match the power and flexibility of the full, feature-rich reactivity API which ships with Vue 3. And we’ll see why in the next sections.

Note: because is an ES5-only and un-shimmable feature, Vue 2 doesn’t support IE8 and below.

How Vue 3 Reactivity Works

The reactivity system in Vue 3 was completely rewritten in order to take advantage of the ES6 Proxy and Reflect APIs. The new version exposes a feature-rich reactivity API which makes the system far more flexible and powerful than before.

The Proxy API allows developers to intercept and modify low-level object operations on a target object. A proxy is a clone/wrapper of an object (called target) and offers special functions (called traps), which respond to specific operations and override the built-in behavior of JavaScript objects. If you still need to use the default behavior, you can use the corresponding Reflection API, whose methods, as the name suggests, reflect those of the Proxy API. Let’s explore an example to see how these APIs are used in Vue 3:

Here’s a CodePen example.

To create a new proxy, we use the constructor. It takes two arguments: the target object ( object) and the handler object, which defines which operations will be intercepted ( and operations). In the object, we use the and traps to track when a property is read and when a property is modified/added. We set console statements to ensure that the methods work correctly.

The and traps take the following arguments:

  • : the target object which is wrapped by the proxy
  • : the property name
  • : the property value (this argument is used only for set operations)
  • : the object on which the operation takes place (usually the proxy)

The Reflect API methods accepts the same arguments as their corresponding proxy methods. They’re used to implement the default behavior for the given operations, which for the trap is returning the property name and for the trap is returning if the property was set or if not.

The commented and functions are specific to Vue and are used to track when a property is read and when a property is modified/added. As a result, Vue re-runs the code that’s using that property.

In the last part of the example, we use a console statement to output the original object. Then we use another statement to read the property of the object. Next, we modify the property and create a new property. Finally, we output the object again to see that it has been updated correctly.

And this is how Vue 3 reactivity works in a nutshell. Of course, the real implementation is way more complex, but hopefully the example presented above is enough for you to grasp the main idea.

There’s also a couple of considerations when you use Vue 3 reactivity:

  • it only works on browsers supporting ES6+
  • the reactive proxy isn’t equal to the original object

Exploring the Vue 3 Reactivity API

Finally, we get to the Vue 3 reactivity API itself. In the following sections, we’ll explore the API methods divided into logical groups. I put methods in groups because I think they’re easier to remember when presented in that way. Let’s start with the basics.

Basic Methods

The first group includes the most basic methods for controlling data reactivity:

  • takes a primitive value or a plain object and returns a reactive and mutable ref object. The ref object has only one property that points to the primitive value or the plain object.
  • takes an object and returns a reactive copy of the object. The conversion is deep and affects all nested properties.
  • takes a ref or an object (plain or reactive) and returns a readonly object to the original. The conversion is deep and affects all nested properties.
  • returns the object itself and prevents it from being converted to a proxy object.

Let’s now see these methods in action:

See the Pen
Vue 3 Reactivity API 1 Edited by SitePoint (@SitePoint)
on CodePen.

In this example, we explore the use of the four basic reactivity methods.

First, we create a ref object with a value of . Then, in the view, we put two buttons which increment and decrement thecounter’s value. When we use these buttons, we see that the counter is truly reactive.

Second, we create a reactive object. Then, in the view, we put two input controls for editing a person’s and a person’s respectively. As we edit the person’s properties, they’re updated immediately.

Third, we create a readonly object. Then, in the view, we set a button for doubling the value of the ‘s property. But when we click the button, an error message is shown in the console, telling us that the object is readonly and that we can’t modify its properties.

Finally, we create an object, which we don’t want to convert to proxy, and mark it as raw. It contains all alphabet letters with their corresponding numbers (for brevity, only the first three letters are used here). This order is unlikely to be changed, so we intentionally keep this object plain, which is good for the performance. We render the object content in a table and set a button that changes the value of property to . We do this to show that although the object can be modified, this doesn’t lead to view re-rendering.

is great for objects we don’t require to be reactive, such as a long list of country codes, color names and their corresponding hexadecimal numbers, and so on.

Lastly, we use the type check methods, described in the next section, to test and determine the type of each object we’ve created. We fire these checks, when the app renders initially, by using the lifecycle hook.

Type Check Methods

This group contains all four type checkers mentioned above:

  • checks if a value is a ref object.
  • checks if an object is a reactive proxy created by or created by by wrapping another proxy created by .
  • checks if an object is a readonly proxy created by .
  • checks if an object is a proxy created by or .

More Refs Methods

This group contains additional ref methods:

  • returns the value of a ref.
  • executes any effects tied to a manually.
  • creates a customized ref with explicit control over its dependency tracking and updates triggering.

Shallow Methods

The methods in this group are “shallow” equivalents of the , , and :

  • creates a ref which tracks only its property without making its value reactive.
  • creates a reactive proxy which tracks only its own properties excluding nested objects.
  • creates a readonly proxy which makes only its own properties readonly excluding nested objects.

Let’s make these methods easier to understand by examining the following example:

See the Pen
Vue 3 Reactivity API 2 Edited by SitePoint (@SitePoint)
on CodePen.

This example starts with the creation of a shallow ref object. Then, in the view, we add two input controls to edit its and properties. But as we try to modify them, we see that they don’t update. To fix that we add a button which changes the whole object with all of its properties. Now it works. This is because the ‘s content ( and as individual properties) is not converted to a reactive object but the mutation of the (the object as a whole) is still tracked.

Next, we create a shallow reactive proxy which contains the and properties and a nested object with the and properties. Then, in the view, we set an input control for each property. When we modify the and properties, we see that they’re reactively updated. But when we try to modify the and properties, we see that they’re not tracked.

Lastly, we create a shallow readonly object with the same properties as . Here, when we try to modify the or property, an error message is shown in the console telling us that the object is readonly and we can’t modify its properties. On the other hand, the and properties can be modified without a problem.

The nested object, from both of the last examples, isn’t affected by the conversion, and it’s kept plain. This means that it can be freely modified but none of its modifications will be tracked by Vue.

Conversion Methods

The next three methods are used for converting a proxy to ref(s) or a plain object:

  • creates a ref for a property on a source reactive object. The ref keeps the reactive connection to its source property.
  • converts a reactive object to a plain object. Each property of the plain object is a ref pointing to the corresponding property of the original object.
  • returns the raw, plain object of a or proxy.

Let’s see how these conversions works in the following example:

See the Pen
Vue 3 Reactivity API 3 Edited by SitePoint (@SitePoint)
on CodePen.

In this example, we first create a base reactive object, which we’ll use as a source object.

Then we convert the person’s property to a ref with the same name. Then, in the view, we add two input controls — one for the ref and one for the person’s property. When we modify one of them, the other is updated accordingly so the reactive connection between them is kept.

Next, we convert all of a person’s properties to individual refs contained in the object. Then, in the view, we add two input controls again to test one of the refs we’ve just created. As we can see, the personDetails’ is in complete sync with the person’s property, just as in the previous example.

Lastly, we convert the reactivity object to a plain object. Then, in the view, we add an input control for editing the rawPerson’s property. But as we can see, the converted object is not tracked by Vue.

Computed and Watch Methods

The last group of methods are for computing complex values and “spying” on certain value(s):

  • takes a getter function as argument and returns an immutable reactive ref object.
  • runs a function immediately and reactively tracks its dependencies and re-runs it whenever the dependencies are changed.
  • is the exact equivalent of the Options API and the corresponding option. It’s watching for a specific data source and applies side effects in a callback function when the watched source has changed.

Let’s consider the following example:

See the Pen
Vue 3 Reactivity API 4 Edited by SitePoint (@SitePoint)
on CodePen.

In this example, we create a computed variable which bases its computation on the and refs. Then, in the view, we add two input controls for editing the two parts of the full name. And as we can see, when we modify whichever part, the is re-calculated and the result is updated.

Next, we create a ref and set a watch effect for it. Every time is modified, the effect will run the callback function. To prove that, in the view, we add a button that increments the volume by one. We set a condition in the callback function that tests whether the volume’s value can be divided into 3, and when it returns true an alert message is shown. The effect is run once when the app is initiated and the volume’s value is set, and then again every time the volume’s value is modified.

Lastly, we create a ref and set a watch function to track it for changes. As soon as the changes, the callback function will be executed. In this example, we add a button that toggles the state between and . Every time this happens, an alert message is shown.

and look pretty much identical in terms of functionality, but they have some distinct differences:

  • treats all reactive properties included in the callback function as dependencies. So if the callback contains three properties, they’re all tracked for changes implicitly.
  • tracks only the properties that we’ve included as arguments in the callback. Also, it provides both the previous and current value of the watched property.

As you can see, the Vue 3 reactivity API offers plenty of methods for a variety of use cases. The API is quite large, and in this tutorial I’ve only explored the basics. For a more in-depth exploration, details and edge cases, visit the Reactivity API documentation.

Conclusion

In this article, we covered what a reactivity system is and how it’s implemented in Vue 2 and Vue 3. We saw that Vue 2 has some drawbacks that are successfully resolved in Vue 3. Vue 3 reactivity is a complete rewrite based on the modern JavaScript features. Let’s summarize its advantages and disadvantages.

Advantages:

  • It can be used as a standalone package. You can use it with React, for example.
  • It offers much more flexibility and power thanks to its feature-rich API.
  • It supports more data structures (Map, WeakMap, Set, WeakSet).
  • It has better performance. Only the needed data is made reactive.
  • Data manipulation caveats from Vue 2 are resolved.

Disadvantages:

  • It only works on browsers supporting ES6+.
  • The reactive proxy doesn’t equal to the original object in terms of identity comparison ().
  • It requires more code compared to the Vue 2 “automatic” reactivity.

The bottom line is that Vue 3 reactivity is a flexible and powerful system, which can be used both by Vue and non-Vue developers. Whatever your case is, just grab it and start building awesome things.

Sours: https://www.sitepoint.com/vue-3-reactivity-system/

3 reactive() vue

Pushed it apart, inserted my fingers into it, but then our seventh participant cut me off, - Come on faster, I have no strength to endure. I entered her, inside there was a heat, like in a stove, her vagina was ribbed inside like a washboard, like footprints in the sand from a receding. Wave, before me it was pretty stretched, but I still felt its density, the elasticity of the walls.

I easily went under her uterus, and she groaned languidly, opened her eyes wide in surprise, and said, - and you.

Vue 3 Composition API: Ref vs Reactive

I have never seen such a rich setting. Margot loudly shouted to Michael: Are you doing well. He said he was finishing soon.

Similar news:

Fuck me. Oh god. no.



2678 2679 2680 2681 2682