This article is mainly for those who do not understand or have not been exposed to the Vue responsive source code. Its main purpose is to have a basic understanding of the responsive principle of Vue. If you are asked such questions in an interview, you will know what the interviewer wants you to answer? PS: If there is anything wrong in the article, you are welcome to correct it. Responsive understanding Responsiveness, as the name implies, means that data changes will cause the view to be updated. This article mainly analyzes the implementation of object and array responsiveness in Vue2.0. We will leave dependency collection and view update to the next article. In Vue, the responsive data we refer to generally refers to array type and object type data. Vue internally hijacks the properties of an object through the Object.defineProperty method, and the array is implemented by overriding the array method. Let's simply implement it below. First, we define the data that needs to be intercepted. const vm = new Vue({ data () { return { count: 0, person: { name: 'xxx' }, arr: [1, 2, 3] } } }) let arrayMethods function Vue (options) { // Only consider the operation of data here let data = options.data if (data) { data = this._data = typeof data === 'function' ? data.call(this) : data } observer (data) } function observer(data) { if (typeof data !== 'object' || data === null) { return data } if (data.__ob__) { // The existence of the __ob__ attribute indicates that it has been intercepted return data } new Observer(data) } Please continue reading below for the implementation and function of arrayMethods, Observer, and __ob__ Implementing the Observer Classclass Observer { constructor (data) { Object.defineProperty(data, '__ob__', { // Define the __ob__ property on data, which is needed in array hijacking enumerable: false, // Not enumerable configurable: false, // Not configurable value: this // The value is the Observer instance }) if (Array.isArray(data)) { //Intercept the array data.__proto__ = arrayMethods //Prototype inheritance this.observerArray(data) } else { // Object interception this.walk(data) } } walk (data) { const keys = Object.keys(data) for(let i = 0; i < keys.length; i++) { const key = keys[i] defineReactive(data, key, data[key]) } } observerArray (data) { // intercept each item in the array data.forEach(value => observer(value)) } } Object interceptionA few points to note about object hijacking:
//Intercept function of processing object defineReactive(data, key, value) { observer(value) // If value is still an object type, you need to recursively hijack Object.defineProperty(data, key, { get() { return value }, set(newValue){ if (newValue === value) return value = newValue observer(newValue) // If the newValue value is also an object type, it needs to be hijacked} }) } Array hijackingA few points to note about array hijacking:
const oldArrayPrototype = Array.prototype arrayMethods = Object.create(oldArrayPrototype) const methods = ['push', 'pop', 'shift', 'unshift', 'splice', 'sort', 'reverse'] // Methods that can change the original array methods.forEach(method => { arrayMethods[methods] = function (...args) { const result = oldArrayPrototype[methods].call(this, ...args) const ob = this.__ob__ // this is the array that calls the method let inserted; // The collection of newly added items in the array needs to be intercepted switch(methods) { case 'push': case 'unshift': inserted = args case 'splice': inserted = args.slice(2) // Because the second parameter of splice is the one that is added} if (inserted) { ob.observerArray(inserted) } return result } }) Principle Summary In the interview, if we need to hand-write the responsiveness principle of Vue, the above code is enough. However, by learning the source code of Vue, if we can give the following summary answers in the interview, we will be more favored by the interviewer. The responsive principle of Vue 2.0 source code:
Vue 3.0 source code responsive principle:
const handler = { get (target, key) { if (typeof target[key] === 'object' && target[key] !== null) { return new Proxy(target[key], handler) } return Reflect.get(target, key) }, set (target, key, value) { if(key === 'length') return true console.log('update') return Reflect.set(target, key, value) } } const obj = { arr: [1, 2, 3], count: { num: 1 } } // obj is the target object of the proxy, handler is the configuration object const proxy = new Proxy(obj, handler) This is the end of this article on the detailed explanation of the data responsiveness principle of Vue. For more relevant Vue data responsiveness content, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future! You may also be interested in:
|
<<: Docker learning method steps to build ActiveMQ message service
>>: MySQL 5.7.16 installation and configuration method graphic tutorial (Ubuntu 16.04)
Table of contents Preface think Library directory...
Table of contents Preface Six features of JSON.st...
Table of contents Function call optimization Func...
This article shares the specific code of Vue to i...
In web design, we often use arrows as decoration ...
Frequently asked questions Access denied for user...
In order to improve user experience and ease of us...
Preface In fact, I have never encountered this ki...
Table of contents 0. The kernel tree that comes w...
Table of contents Preface 1. Understanding with e...
To set the line spacing of <p></p>, us...
1. Check the PHP version after entering the termi...
I struggled with a problem for a long time and re...
[LeetCode] 197.Rising Temperature Given a Weather...
This article uses an example to describe how MySQ...