Home Web Front-end JS Tutorial How to make Vue array mutation function

How to make Vue array mutation function

May 31, 2018 am 10:31 AM
Function Mutations array

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() {
}
Copy after login

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
 })
})
Copy after login

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
 })
}
Copy after login

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);
Copy after login

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()
Copy after login

in the source code is the corresponding doSomething()

在该代码中,清清楚楚的写了2个单词的注释notify change,不认识这2个单词的同学就百度一下嘛,这里就由我代劳了,这俩单词的意思是发布改变!每次调用了该方法,都会求出值,然后做一些其他的事情,比如发布改变与观察新增的元素,响应的其他过程在本篇就不讨论了。

[
 'push',
 'pop',
 'shift',
 'unshift',
 'splice',
 'sort',
 'reverse'
]
Copy after login

目前一共有这么些方法,只要用对方法就能改变女神的姿势哟!

相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!

推荐阅读:

怎样使用Vue实现树形视图数据

JS对DOM树实现遍历有哪些方法

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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to remove duplicate elements from PHP array using foreach loop? How to remove duplicate elements from PHP array using foreach loop? Apr 27, 2024 am 11:33 AM

The method of using a foreach loop to remove duplicate elements from a PHP array is as follows: traverse the array, and if the element already exists and the current position is not the first occurrence, delete it. For example, if there are duplicate records in the database query results, you can use this method to remove them and obtain results without duplicate records.

PHP array key value flipping: Comparative performance analysis of different methods PHP array key value flipping: Comparative performance analysis of different methods May 03, 2024 pm 09:03 PM

The performance comparison of PHP array key value flipping methods shows that the array_flip() function performs better than the for loop in large arrays (more than 1 million elements) and takes less time. The for loop method of manually flipping key values ​​takes a relatively long time.

PHP array multi-dimensional sorting practice: from simple to complex scenarios PHP array multi-dimensional sorting practice: from simple to complex scenarios Apr 29, 2024 pm 09:12 PM

Multidimensional array sorting can be divided into single column sorting and nested sorting. Single column sorting can use the array_multisort() function to sort by columns; nested sorting requires a recursive function to traverse the array and sort it. Practical cases include sorting by product name and compound sorting by sales volume and price.

The Art of PHP Array Deep Copy: Using Different Methods to Achieve a Perfect Copy The Art of PHP Array Deep Copy: Using Different Methods to Achieve a Perfect Copy May 01, 2024 pm 12:30 PM

Methods for deep copying arrays in PHP include: JSON encoding and decoding using json_decode and json_encode. Use array_map and clone to make deep copies of keys and values. Use serialize and unserialize for serialization and deserialization.

Best Practices for Deep Copying PHP Arrays: Discover Efficient Methods Best Practices for Deep Copying PHP Arrays: Discover Efficient Methods Apr 30, 2024 pm 03:42 PM

The best practice for performing an array deep copy in PHP is to use json_decode(json_encode($arr)) to convert the array to a JSON string and then convert it back to an array. Use unserialize(serialize($arr)) to serialize the array to a string and then deserialize it to a new array. Use the RecursiveIteratorIterator to recursively traverse multidimensional arrays.

What is GateToken(GT) currency? Introduction to GT coin functions and token economics What is GateToken(GT) currency? Introduction to GT coin functions and token economics Jul 15, 2024 pm 04:36 PM

What is GateToken(GT) currency? GT (GateToken) is the native asset on the GateChain chain and the official platform currency of Gate.io. The value of GT coins is closely related to the development of Gate.io and GateChain ecology. What is GateChain? GateChain was born in 2018 and is a new generation of high-performance public chain launched by Gate.io. GateChain focuses on protecting the security of users' on-chain assets and providing convenient decentralized transaction services. GateChain's goal is to build an enterprise-level secure and efficient decentralized digital asset storage, distribution and transaction ecosystem. Gatechain has original

Application of PHP array grouping function in data sorting Application of PHP array grouping function in data sorting May 04, 2024 pm 01:03 PM

PHP's array_group_by function can group elements in an array based on keys or closure functions, returning an associative array where the key is the group name and the value is an array of elements belonging to the group.

The role of PHP array grouping function in finding duplicate elements The role of PHP array grouping function in finding duplicate elements May 05, 2024 am 09:21 AM

PHP's array_group() function can be used to group an array by a specified key to find duplicate elements. This function works through the following steps: Use key_callback to specify the grouping key. Optionally use value_callback to determine grouping values. Count grouped elements and identify duplicates. Therefore, the array_group() function is very useful for finding and processing duplicate elements.

See all articles