The second-generation and third-generation Vue response systems are stronger than one wave. Is the previous wave dead? (under)
Please indicate the source for reprinting: Grape City official website, Grape City provides developers with professional development tools, solutions and services, and empowers developers.
Original reference: https://www.sitepoint.com/vue-3-reactivity-system/
In the previous section, we made a comparison between the reactive system in Vue2 and Vue3, and took you to understand the working principle of the reactive system. Today we will further explore the reactive system API in Vue3, in order for everyone to better understand and Study, group the methods and summarize them.
Including the most basic method of controlling data response
- ref accepts a primitive value or an ordinary object, and then returns a responsive and variable ref object. The ref object has only one value pointing to the original value or the attribute of the pure object.
- Reactive receives an object and returns a reactive copy of the object. This content affects all nested properties.
- readonly accepts a ref or an object (plain or reactive), and returns a read-only object to the original object, and will affect all nested properties.
- markRaw returns the object itself and prevents it from being converted into a proxy object.
actually uses :
In this example, we explored the use of four basic reactive methods.
1. Create a counterref object with a value of 0. Then place two buttons in the view to increase and decrease the value of the counter. When used, the counter has no effect.
2. Next, create a person response object. Place two input controls in the view, which are used to edit a person's name and a person's age, respectively. It will be updated immediately when we edit the attributes of the staff.
3. Create a math read-only object. Then set a button in the view to double the PI attribute value of math. The object can only be read and cannot be modified.
4. Create an alphabetNumbers object and mark it as raw. Take the first three content. Set a button to change the value of Bproperty to 3. We will find that we can modify the object, but will not cause the view to re-render.
The markRaw method is very suitable for objects that we do not need to respond to, such as a long list of country/region codes, color names and their corresponding hexadecimal numbers, and so on.
5. Test and determine the type of each object we create, and use the lifecycle hook of onMounted() to trigger these checks.
Type checking method
This group contains all four type checkers mentioned above:
- isRef checks whether the value is a reference object
- isReactive checks whether the object is created by reactive or readonly by wrapping the reactive proxy created by another proxy created by reactive
- isReadonly checks whether the object is created by a read-only proxy readonly
- isProxy checks whether the object is a proxy created by reactive or readonly
More reference methods
This group contains other reference methods:
- unref returns the referenced value
- triggerRef performs any effect related to shallowRef manual
- customRef creates an explicit control with a custom reference, and explicitly controls its dependency tracking and updates the trigger
The methods in this group are ref, reactivity and readonly:
- shallowRef creates a ref that only tracks its value attribute without making its value responsive
- shallowReactive creates a reactive proxy that only tracks its own attributes (not including nested objects)
- shallowReadonly creates a read-only proxy that only makes its attributes read-only (not including nested objects)
Experience the use of these methods through the following examples:
This example starts by creating a shallow reference object for settings, adding two input controls to the view to edit its width and height properties. But this property cannot be modified. To solve this problem, add a button that can change the entire object and all its properties.
Then create a settingsA shallow reactive proxy, including width and height attributes, and nested object coords with x and y attributes. Set an input control for each attribute in the view. When the width and height properties are modified, there is a response update, but there is no change when the x and y properties are modified.
Finally, a shallow read-only object of settingsB is created with the same attributes as settingsA. But here the widthorheight attribute is only readable and cannot be modified. The x and y attributes can be modified normally.
The nested object coords in the last two examples are not affected by the conversion, Vue does not track any changes to it, and can be modified freely.
The next three methods are used to convert the proxy into a ref or ordinary object:
- toRef creates a reference to the attribute on the source response object. The reference keeps the responsive connection to its source attribute.
- toRefs converts the response object into a normal object. Each attribute of the ordinary object is a ref that points to the corresponding attribute of the original object.
- toRaw returns the original object of areactive or readonlyproxy.
In the following example, we will show how these conversions work:
In this example
1. Create a basic person reaction object and use it as the source object.
2. Convert the name property to ref with the same name. Add two input controls to the view-one for name reference and the other for nameproperty. When one of them is modified, the other will also be updated.
3. Convert all the attributes of one of the persons into references contained in the personDetails object. Add two input controls again in the view to test one of the references you just created. It is found that personDetailsage is completely synchronized with the person's age attribute.
4. Convert person responsive objects into rawPerson ordinary objects. Add an input control to the view to edit the hobby property of rawPerson, Vue does not track it.
Calculation and monitoring methods
The last set of methods is used to calculate complex values and monitor certain values:
- computed takes a getter function as a parameter and returns an unchanging responsive ref object.
- watchEffect runs a function immediately, tracks its dependencies in a responsive manner, and reruns it when the dependencies change.
- watch is exactly equivalent to the Options API this.$watch and the corresponding watch option. It monitors a specific data source and applies side effects in the callback function when the monitored source changes.
Let's continue to look at the following example:
In this example, we have created a fullName calculation variable, which is calculated based on firstName and lastName. Two input controls are added to the view to edit the two parts of the full name. Modifying any part of fullName will recalculate and update the result.
Next, we create a volumeref and set the viewing effect for it, and the callback function will be run every time the volume is modified. To verify that the process is like this, we add a button to the view that doubles the volume. Then set a condition in the callback function to test whether the value of the volume can be divided into three parts. When it returns true, an alert message will be displayed.
Finally, we create a stateref and set a watch function to track its changes. The state changes the execution function. In addition, we added a button to switch the state between playing and paused. If the status is switched, there will be a prompt.
Some differences between watchEffect and watch:
- watchEffect treats all responsive properties contained in the callback function as dependencies. Therefore, if the callback contains three properties, all property changes will be tracked implicitly.
- Watch only tracks the attributes we include as callback parameters. In addition, it also provides the previous and current values of the watched attribute.
We will find that the Vue 3 reactive API provides many methods for various use cases, and there are many API content. In this tutorial, we only discuss the basics. For more in-depth exploration, details and edge cases, please visit the Reactivity API documentation.
In this article, we introduced what a response system is and how to implement it in Vue 2 and Vue 3. Some of the flaws in Vue 2 have been resolved in Vue 3. Finally, let us summarize the advantages and disadvantages of the Vue3 responsive system.
- Can be used as a standalone package. For example, you can use it with React
- With its feature-rich API, a lot of functions can be realized with high flexibility
- Support more data structures (Map, WeakMap, Set, WeakSet)
- With better performance, only the required data is responsive
Resolved data manipulation warnings in Vue 2
- Only available for browsers that support ES6+
- In terms of comparison (===), the reactive proxy is not equal to the original object
- Compared to Vue 2's "automatic" reactivity, more code is required