An article explaining the principle of reactivity in Vue in detail
This article will help you learn Vue and gain an in-depth understanding of the responsiveness principles in Vue. I hope it will be helpful to you!
This article commemorates the passing of responsive syntax sugar
Without further ado, let’s get straight to the point. Responsiveness is Applications in daily development are very common. Here is a simple example:
let a=3 let b=a*10 console.log(b)//30 a=4 console.log(b)//40
At this time we want b=4*10, which is obviously not possible, even if we add a ## in front #var will only
variable promotion, the value we give will not be promoted.
import { reactive } from 'vue' let state = reactive({ a: 3 }) let b = computed(() => state.a * 10) console.log(b.value) // 30 state.a = 4 console.log(b.value) // 40Only a simple
responsive API can achieve the effect of tracking changes. [Related recommendations:
vuejs video tutorial, web front-end development]
Analyze reactive
In fact, Vue3reactive is essentially a
publish-subscribe model
reactive system will automatically trigger an update of the view. This is because it tracks data changes in the dependency graph and achieves this by associating it with updates to the view
class Dep{ constructor(value){ this.subscribers=new Set() this._value=value } get value(){ this.depend() return this._value } set value(newValue){ this._value=newValue this.notify() } depend(){ if(activeEffect){ this.subscribers.add(activeEffect) } } notify(){ this.subscribers.forEach(effect=>{ effect() }) } }Let’s analyze this code:
When the value of the variable changes, it can automatically notify all subscribers to updateDefine a
- subscribe
attribute as a subscriber list to store all Subscriber information
- depend
function is used to manage dependency relationships, that is, the variable
- notify
function on which the subscriber depends is used as a notification The value of this variable has changed for all subscribers
Vue2’s Object.defineProperty
In fact, in the Vue2 period, responsiveness was implemented byObject.defineProperty, but in Vue3 it was switched to
Proxy, let’s wait and see the reason combined with the actual code; let’s first take a look at how Vue2 is implemented:
function reactive(raw){ Object.keys(raw).forEach(ket=>{ const dep=new Dep() let value=raw[key] Object.definProperty(raw,key,{ get(){ dep.depend() return value }, //当属性发生 set(newValue){ value=newValue dep.notify() } }) }) //这时候返回的原始对象已经具有响应性 return raw }Such a simple reactive API is implemented
But the shortcomings here are obvious:
In Vue 2.x, the object passed in will be directly changed by Vue.observable But in Vue3, it is Will return a responsive proxy, but directly changing the source object is still unresponsive
Of course, this is a historical limitation. At that time, ES5 could only chooseWhen When we
- add or delete
Unable to detect thethe properties of the object, Vue2's responsiveness cannot be detected. Since Vue will perform getter/setter conversion on the property when initializing the instance, the property must be in
dataOnly when it exists on the object can Vue convert it into a responsive
- subscript and length changes of the array
Object.definProperty, but in the ES6 version, there are more
Proxy. At this time, Vue’s response The formula has been upgraded
Vue3’s Proxy
Vue3 usesProxy to monitor data changes. Compared with Vue2, it not only solves In addition to the above problems, there are also these advantages:
Let's take a look at what the actual code looks like:No need to use
- vue.$set
Comprehensive array change detection, eliminating invalid boundary conditions in Vue2to trigger reactivity, which makes the code look more
Introduction- Reduces the amount of responsive code written in Vue3, which makes our development more convenient
const reactiveHandles={ get(target,key,receiver){ const dep=getDep(target,key) dep.depend() return Reflect.get(target,key,receiver) }, set(target,key,value,receiver){ const dep=getDep(target,key) const result=Reflect.set(target,key,value,receiver) dep.notify() return result } }The responsive way is to
collect dependencies on objects. The essence of Vue3 responsiveness
ref
There is a sentence in the official documentation: The various limitations ofreactive() are ultimately because JavaScript cannot function The "reference" mechanism for all value types, and the limitation of reactive is:
And this time it is neededcan only handle observable data structures, such as arrays and objects; and unobservable data structures , such as primitive data types, they cannot be monitored
- Can only process data defined in the component where it is located, and cannot process global variables
ref is here, ref was born for
basic data type, which makes up for the shortcomings of reactive. To put it simply, ref is more suitable for simple single variable values (but in actual development Most of the time it’s just refs. Hahahaha
(Learning video sharing: vuejs introductory tutorial, Basic programming video)
The above is the detailed content of An article explaining the principle of reactivity in Vue in detail. For more information, please follow other related articles on the PHP Chinese website!

Vue.js is closely integrated with the front-end technology stack to improve development efficiency and user experience. 1) Construction tools: Integrate with Webpack and Rollup to achieve modular development. 2) State management: Integrate with Vuex to manage complex application status. 3) Routing: Integrate with VueRouter to realize single-page application routing. 4) CSS preprocessor: supports Sass and Less to improve style development efficiency.

Netflix chose React to build its user interface because React's component design and virtual DOM mechanism can efficiently handle complex interfaces and frequent updates. 1) Component-based design allows Netflix to break down the interface into manageable widgets, improving development efficiency and code maintainability. 2) The virtual DOM mechanism ensures the smoothness and high performance of the Netflix user interface by minimizing DOM operations.

Vue.js is loved by developers because it is easy to use and powerful. 1) Its responsive data binding system automatically updates the view. 2) The component system improves the reusability and maintainability of the code. 3) Computing properties and listeners enhance the readability and performance of the code. 4) Using VueDevtools and checking for console errors are common debugging techniques. 5) Performance optimization includes the use of key attributes, computed attributes and keep-alive components. 6) Best practices include clear component naming, the use of single-file components and the rational use of life cycle hooks.

Vue.js is a progressive JavaScript framework suitable for building efficient and maintainable front-end applications. Its key features include: 1. Responsive data binding, 2. Component development, 3. Virtual DOM. Through these features, Vue.js simplifies the development process, improves application performance and maintainability, making it very popular in modern web development.

Vue.js and React each have their own advantages and disadvantages, and the choice depends on project requirements and team conditions. 1) Vue.js is suitable for small projects and beginners because of its simplicity and easy to use; 2) React is suitable for large projects and complex UIs because of its rich ecosystem and component design.

Vue.js improves user experience through multiple functions: 1. Responsive system realizes real-time data feedback; 2. Component development improves code reusability; 3. VueRouter provides smooth navigation; 4. Dynamic data binding and transition animation enhance interaction effect; 5. Error processing mechanism ensures user feedback; 6. Performance optimization and best practices improve application performance.

Vue.js' role in web development is to act as a progressive JavaScript framework that simplifies the development process and improves efficiency. 1) It enables developers to focus on business logic through responsive data binding and component development. 2) The working principle of Vue.js relies on responsive systems and virtual DOM to optimize performance. 3) In actual projects, it is common practice to use Vuex to manage global state and optimize data responsiveness.

Vue.js is a progressive JavaScript framework released by You Yuxi in 2014 to build a user interface. Its core advantages include: 1. Responsive data binding, automatic update view of data changes; 2. Component development, the UI can be split into independent and reusable components.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Dreamweaver Mac version
Visual web development tools

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.
