This time I will show you how to make Vuearraymutation function, what are the notes for making Vue array mutation function, the following is a practical case, let’s take a look .
Preface
Many students who are new to using Vue will find that when changing the value of the array, the value does change, but the view But he was indifferent. Is it because the array is too cold?
After checking the official documents, I discovered that it’s not that the goddess is too cold, but that you didn’t use the right method.
#It seems that if you want the goddess to move by herself, the key is to use the right method. Although the method has been given in the official document, I am really curious. If you want to unlock more postures, you must first get into the heart of the goddess, so I came up with the idea of exploring the responsive principle of Vue. (If you are willing to peel off my heart layer by layer. You will find that you will be surprised... I am addicted to the howling of ghosts and can't extricate myself QAQ).
Front tip, Vue’s responsiveness principle mainly uses ES5’s Object.defineProperty. Uninformed students can view relevant information.
Why does the array not respond?
If you think about it carefully, Vue's response is based on Object.definePropery. This method mainly modifies the description of the object's properties. Arrays are actually objects, and by defining the properties of the array, we should be able to produce responsive effects. Test your idea first, roll up your sleeves and get started.
const arr = [1,2,3]; let val = arr[0]; Object.defineProperty(arr,'0',{ enumerable: true, configurable: true, get(){ doSomething(); return val; }, set(a){ val = a; doSomething(); } }); function doSomething() { }
Then enter arr, arr[0] = 2, arr respectively in the console, you can see the results as shown below.
Hey, everything is as expected.
Next, after seeing this code, some students may have questions, why don’t this[0] be returned directly in the get() method? But should we use val to return the value? Think about it carefully, damn! ! ! It's almost an infinite loop. Think about it, get() itself gets the value of the current attribute. Isn't calling this[0] in get() equivalent to calling the get() method again? It's so scary, so scary, it scares the laborers to death.
Although the goddess in your imagination may have this posture, the goddess in front of you is indeed not in this posture. How can a person like me, whose attributes are clearly exposed, guess the goddess's mind? Why not respond to the data like this? Perhaps because arrays and objects are still different, defining the properties of arrays may cause some troubles and bugs. Or it may be because a large amount of data may be generated during the interaction process, resulting in overall performance degradation. It is also possible that the author can use other methods to achieve the effect of data response after weighing the pros and cons. Anyway, I can't figure it out.
Why can I respond just by calling the native method of the array?
Why can the data respond by using these array methods? Let’s take a look at the source code of the array part first.
Simply speaking, the function of def is to redefine the value of the object attribute.
//array.js import { def } from '../util/index' const arrayProto = Array.prototype export const arrayMethods = Object.create(arrayProto) //arrayMethods是对数组的原型对象的拷贝, //在之后会将该对象里的特定方法进行变异后替换正常的数组原型对象 /** * Intercept mutating methods and emit events */ [ 'push', 'pop', 'shift', 'unshift', 'splice', 'sort', 'reverse' ] .forEach(function (method) { // cache original method //将上面的方法保存到original中 const original = arrayProto[method] def(arrayMethods, method, function mutator (...args) { const result = original.apply(this, args) const ob = this.ob let inserted switch (method) { case 'push': case 'unshift': inserted = args break case 'splice': inserted = args.slice(2) break } if (inserted) ob.observeArray(inserted) // notify change ob.dep.notify() return result }) })
Post the code of the def part
/** * Define a property. */ export function def (obj: Object, key: string, val: any, enumerable?: boolean) { Object.defineProperty(obj, key, { value: val, enumerable: !!enumerable, writable: true, configurable: true }) }
array.js mutates some methods of the array. Let’s take the push method as an example. The first thing is to use original = arrayProto['push'] to save the native push method.
Then it’s time to define the mutation method. For deffunction, if you don’t go into details, def(arrayMethods,method,function(){}), this function can be roughly expressed as arrayMethods[method] = function mutator(){};
Assuming that the push method is called later, the mutator method is actually called. In the mutator method, the first thing is to call the saved native push method. original, first find the actual value. A bunch of text looks really abstract, so write a low-profile version of the code to express the meaning of the source code.
const push = Array.prototype.push; Array.prototype.push = function mutator (...arg){ const result = push.apply(this,arg); doSomething(); return result } function doSomething(){ console.log('do something'); } const arr = []; arr.push(1); arr.push(2); arr.push(3);
The result viewed in the console is:.
Then the code
const ob = this.ob let inserted switch (method) { case 'push': case 'unshift': inserted = args break case 'splice': inserted = args.slice(2) break } if (inserted) ob.observeArray(inserted) // notify change ob.dep.notify()
in the source code is the corresponding doSomething()
在该代码中,清清楚楚的写了2个单词的注释notify change,不认识这2个单词的同学就百度一下嘛,这里就由我代劳了,这俩单词的意思是发布改变!每次调用了该方法,都会求出值,然后做一些其他的事情,比如发布改变与观察新增的元素,响应的其他过程在本篇就不讨论了。
[ 'push', 'pop', 'shift', 'unshift', 'splice', 'sort', 'reverse' ]
目前一共有这么些方法,只要用对方法就能改变女神的姿势哟!
相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!
推荐阅读:
The above is the detailed content of How to make Vue array mutation function. For more information, please follow other related articles on the PHP Chinese website!