search
HomeWeb Front-endJS TutorialHow to make Vue array mutation function
How to make Vue array mutation functionMay 31, 2018 am 10:31 AM
FunctionMutationsarray

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中文网其它相关文章!

推荐阅读:

怎样使用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
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
使用JavaScript实现自动登录功能使用JavaScript实现自动登录功能Jun 15, 2023 pm 11:52 PM

随着互联网的发展,人们越来越依赖网络,大部分时间都在使用各种各样的网站和应用程序,这也使得我们需要记住很多账号和密码。为了方便用户的使用,很多网站提供了自动登录功能,让用户免除频繁输入账号和密码的烦恼。本文将介绍使用JavaScript实现自动登录功能的方法。一、登录流程分析在开始实现自动登录功能之前,我们需要了解整个登录流程。一般情况下,一个网站的登录流程

如何使用PHP实现天气预报功能如何使用PHP实现天气预报功能Jun 27, 2023 pm 05:54 PM

PHP作为一款流行的后端编程语言,在Web开发领域广受欢迎。天气预报功能是一种常见的Web应用场景,基于PHP实现天气预报功能相对简单易懂。本文将介绍如何使用PHP实现天气预报功能。一、获取天气数据API要实现天气预报功能,首先需要获取天气数据。我们可以使用第三方天气API来获取实时、准确的天气数据。目前,国内主流的天气API供应商包括免费的“心知天气”和收

如何使用 Windows Copilot 与剪贴板一起展开、解释、总结或修改复制的文本如何使用 Windows Copilot 与剪贴板一起展开、解释、总结或修改复制的文本Jul 29, 2023 am 08:41 AM

在Copilot目前在Windows11上拥有的少数功能中,也许最有用的功能是允许您交互和调整已复制到剪贴板的文本的功能。这使得将Copilot用作文本编辑和摘要工具变得容易,您可以直接从桌面使用。以下是您需要了解的有关使用Copilot在Windows上解释、修订、扩展和汇总文本的所有信息。如何在WindowsCopilot中使用复制的文本Copilot的预览版让我们第一次很好地了解了Windows对原生AI支持的集成。修改或扩展从其他地方复制的文本的早期功能之一可以通过内容创建、摘要、修订和

未来功能抢先用 Safari 技术预览 173 版本释出未来功能抢先用 Safari 技术预览 173 版本释出Jul 02, 2023 pm 01:37 PM

Apple今日释出了Safari技术预览173版本,涵盖部分可能于Safari17推出的功能。该版本适用于macOSSonoma测试版以及macOSVentura系统,有兴趣的用户可于官方网页下载。Safari技术预览173版于设定中新增了功能标志区块,取代原先开发菜单的实验功能。该区块可让开发者快速地搜索特定功能,并以不同形式将「稳定」、「可供测试」、「预览」或「开发人员」等状态标示出来。重新设计的开发菜单可以帮助创作者更容易找到关键工具,以便建立网页、网页应用程序、其他应用程序中的网页内容、

如何在iPhone上扫描QR码如何在iPhone上扫描QR码Jul 20, 2023 am 09:13 AM

Apple在设备中内置了这个方便的功能,可以从iPhone上的相机轻松访问它,这将允许您自动扫描设备上的QR码。二维码代表快速响应码,本质上是一种二维条形码,可以通过配备内置摄像头的各种智能手机和其他电子设备轻松扫描和解释。扫描二维码后,用户通常会被定向到特定网站或提示激活应用程序中的特定功能。这种令人难以置信的方便功能在现代智能手机(包括Apple的iPhone)中变得越来越普遍,它是用户以最小的努力访问信息,服务或功能的便捷方式。许多公司在实体产品上使用此功能,您可以扫描其产品上的二维码,然

Google Colab将很快使用Codey进行AI编码Google Colab将很快使用Codey进行AI编码Jun 09, 2023 am 10:43 AM

GoogleColab是一个自2017年以来一直在促进Python编程的平台,它将利用Google的高级代码模型Codey引入AI编码功能。Codey基于PaLM2模型构建,对来自外部来源的大型高质量代码数据集进行了精心微调,以提高其在编码任务方面的性能。Colab即将推出的功能包括代码补全、自然语言到代码生成以及代码辅助聊天机器人。最初的重点将放在代码生成上,该功能旨在使用户能够生成更大的代码块并从注释或提示编写整个函数。这旨在减少编写重复代码的需求,允许用户专注于编程和数据科学的更复杂的方面

鸿蒙OS3.0的功能有什么?鸿蒙OS3.0的功能有什么?Jun 29, 2023 pm 10:53 PM

鸿蒙os3.0目前正在测试阶段,很快用户就将迎来新的系统体验了,那么相较于2.0版本,鸿蒙os3.0有什么功能呢?华为鸿蒙3.0包含了多屏协同、性能共享等功能,用户可以获得更加完善的协同体验,同时也能提升手机运行大型游戏或软件的流畅度。另外,它简化了小窗交互方式,并改进通知栏,带给你更为完美的体验,接下来就让小编给大家分析一下华为鸿蒙3.0新功能介绍,一起来了解一下吧。华为鸿蒙3.0功能介绍1、多屏协同:此前鸿蒙2.0可以在电脑手机之间互相切换使用,提高了用户的工作效率和使用体验,但此次的鸿蒙3

win10电脑系统纯版和专业版有什么区别win10电脑系统纯版和专业版有什么区别Jul 19, 2023 am 11:01 AM

win10系统是目前主流的操作系统,也是微软最新的产品,版本很多。其中有网友纠结不知道选择win10纯版还是win10专业版,win10电脑系统纯版和专业版有什么区别。以下小系列将告诉你win10电脑系统纯版和专业版的区别。win10纯版:Win10纯版是网上第三方系统爱好者,在微软原版系统的基础上删除一些自带广告封装的系统。没有多余的软件捆绑,但稳定性可能没有正式版和专业版那么强。最重要的是win10纯版可以在网上下载安装,由民间专家优化,完全免费,功能和专业版没有太大区别。win10专业版:

See all articles

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 agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft