vue3、vue2中nextTick源码解析

nexttick是啥

nextTick是Vue提供的一个全局API,由于Vue的异步更新策略导致我们对数据的修改不会更新,如果此时想要获取更新后的Dom,就需要使用这个方法.
vue的异步更新策略意思是如果数据变化,vue不会立刻更新dom,而是开启一个队列,把组件更新函数保存在队列里,在统一事件循环中发生的所有数据变更会异步的批量更新,这一策略导致我们对数据的修改不会立即体现在dom上,此时如果想要获取更新后的dom状态,就要使用nexttick
nextTick所指定的回调会在浏览器更新DOM完毕之后再执行。即在一次事件循环中,更新了数据,把更新Dom的操作放入队列中,使用了nextTick,则把nextTick里的回调放入队列中,执行完所有的同步代码后,去执行微任务,即依次调用队列里的函数。

函数签名:

nextTick<T = void, R = void>(this: T, fn?: (this: T) => R): Promise<Awaited<R>>:

this:不是参数,是ts中的一个语法,给 this 定义类型。给用于绑定回调函数中的 this 上下文,可以省略。
fn:要异步执行的回调函数,是一个函数,可以省略。
函数返回一个 Promise,Promise 的泛型为 Awaited,表示回调函数执行后的返回值。

使用场景:

  • created中想要获取dom时
  • 响应式数据变化后获取dom更新后的状态,比如希望获取列表更新后的高度
vm.name = 'changed'
vm.$nextTick(()=>{ // 要在更新数据的后面使用console.log(app.innerHTML)
})

vue2、vue3中nexttick源码

简单来讲就是nexttick回调函数使用promise.then方式放入了异步,在所有dom都更新完成后才调用
先上一个小例子,(来自https://b23.tv/AmCLtgx),

async increment() {this.count++;//dom还未更新console.log(document.getElementById('counter').textContent)//0await nextTick();//dom已经更新conosle.log(document.getElementById('counter').textContent)//1

我们先看,响应式数据count改变之后,会发生什么. (具体代码讲解放在代码注释里了,以下为vue3源码)

  1. 让与响应式数据相关连的函数去排队,调用queueJob()
    源码位置:(太长了,只放一部分)
    https://github.com/vuejs/core/blob/main/packages/runtime-core/src/renderer.ts
// 为组件创建一个响应式效果,以便在组件的依赖项发生变化时触发重新渲染,换句话说,就是一个响应式数据改变后, 与它相关联的函数用什么方式去执行
// create reactive effect for renderingconst effect = (instance.effect = new ReactiveEffect(componentUpdateFn,//与响应式数据相关联的函数NOOP,//空函数,,表示没有特定的调度逻辑() => queueJob(update),//响应式数据改变后,不会立刻执行componentUpdateFn,而是让componentUpdateFn去排队,在未来某一时刻执行、instance.scope, // track it in component's effect scope))
  1. 排队函数具体内容
    源码位置:
    https://github.com/vuejs/core/blob/main/packages/runtime-core/src/scheduler.ts

queueJob方法: 把上一步中输入的参数update(也就是job)按特定规则推到queue任务队列里, 调用queueFlush()

export function queueJob(job: SchedulerJob) {// the dedupe search uses the startIndex argument of Array.includes()// by default the search index includes the current job that is being run// so it cannot recursively trigger itself again.// if the job is a watch() callback, the search will start with a +1 index to// allow it recursively trigger itself - it is the user's responsibility to// ensure it doesn't end up in an infinite loop.//先检查queue数组是否为空,或者job是否已经包含在queue数组中。这个检查确保相同的job不会被多次排队。if (!queue.length ||!queue.includes(job,isFlushing && job.allowRecurse ? flushIndex + 1 : flushIndex,)) {if (job.id == null) {//如果job无id属性,把job插入到queue数组末尾queue.push(job)} else {//如果job有id属性,就按照id把job插入到queue数组中特定位置queue.splice(findInsertionIndex(job.id), 0, job)}queueFlush()//刷新队列}
}

queueFlush方法: 把flushJobs(真正刷新队列的函数)放在promise.then里,等同步任务都完成后才真的刷新队列,再执行里面的更新函数

function queueFlush() {//刷新队列方法if (!isFlushing && !isFlushPending) {//当前没有正在进行的刷新操作,并且没有待处理(被挂起)的刷新操作isFlushPending = true//表示有一个刷新操作待处理(被挂起)currentFlushPromise = resolvedPromise.then(flushJobs)}//注意这里是promise,属于微任务,所以会在未来某一时刻异步的执行,因此,当flushjob这个方法真正执行时,其实其他所有的同步代码都已经执行完了
}

flushjob方法:按特定顺序(从父组件更新到子组件遍历并执行任务队列queue中的任务, 并处理执行过程中的任何错误。

function flushJobs(seen?: CountMap) {//循环遍历所有的组件更新函数,去更新所有的组件isFlushPending = falseisFlushing = trueif (__DEV__) {seen = seen || new Map()}// Sort queue before flush.// This ensures that:// 1. Components are updated from parent to child. (because parent is always//    created before the child so its render effect will have smaller//    priority number)// 2. If a component is unmounted during a parent component's update,//    its update can be skipped.queue.sort(comparator)//排序,确保组件从父组件更新到子组件,并允许跳过已卸载组件的更新。// conditional usage of checkRecursiveUpdate must be determined out of// try ... catch block since Rollup by default de-optimizes treeshaking// inside try-catch. This can leave all warning code unshaked. Although// they would get eventually shaken by a minifier like terser, some minifiers// would fail to do that (e.g. https://github.com/evanw/esbuild/issues/1610)const check = __DEV__? (job: SchedulerJob) => checkRecursiveUpdates(seen!, job): NOOPtry {//遍历作业队列。for (flushIndex = 0; flushIndex < queue.length; flushIndex++) {const job = queue[flushIndex]if (job && job.active !== false) {if (__DEV__ && check(job)) {continue}callWithErrorHandling(job, null, ErrorCodes.SCHEDULER)}}} finally {flushIndex = 0queue.length = 0flushPostFlushCbs(seen)isFlushing = falsecurrentFlushPromise = null// some postFlushCb queued jobs!// keep flushing until it drains.if (queue.length || pendingPostFlushCbs.length) {//若queue仍然有作业,或有待处理的后续刷新回调,则递归调用flushjob,直到队列为空且所有回调都执行完毕flushJobs(seen)}}
}

nextTick: 获取queueFlush中用到的resolvedPromise, 用then方法执行nexttick的回调函数,

export function nextTick<T = void, R = void>(this: T,//确保回调函数fn在执行时具有正确的上下文fn?: (this: T) => R,
): Promise<Awaited<R>> {const p = currentFlushPromise || resolvedPromisereturn fn ? p.then(this ? fn.bind(this) : fn) : p
}//如果提供了回调函数 fn,则在 p 的 promise 对象上调用 then 方法。如果有可用的 this 上下文,则使用 bind 方法将 fn 函数绑定到 this 上下文。否则,直接使用 fn。
//如果未提供回调函数(fn 为假值),则直接返回 p 的 promise 对象。

回看一开始的例子,

async increment() {this.count++;//导致组件更新函数入队//dom还未更新console.log(document.getElementById('counter').textContent)//0await nextTick();//导致下面所有代码封装成一个匿名函数,并放到刚才的组件更新函数后面,//因此清空队列的时候,会先把所有的组件全清空后,才会执行nexttick后的延迟的语句或回调函数//dom已经更新conosle.log(document.getElementById('counter').textContent)//1

vue2中netxtick源码位置:
https://github.com/vuejs/vue/blob/main/src/core/util/next-tick.ts
里面用到了优雅降级,可以看看,不多写了

/* globals MutationObserver */import { noop } from 'shared/util'
import { handleError } from './error'
import { isIE, isIOS, isNative } from './env'export let isUsingMicroTask = falseconst callbacks: Array<Function> = []
let pending = falsefunction flushCallbacks() {pending = falseconst copies = callbacks.slice(0)callbacks.length = 0for (let i = 0; i < copies.length; i++) {copies[i]()}
}// Here we have async deferring wrappers using microtasks.
// In 2.5 we used (macro) tasks (in combination with microtasks).
// However, it has subtle problems when state is changed right before repaint
// (e.g. #6813, out-in transitions).
// Also, using (macro) tasks in event handler would cause some weird behaviors
// that cannot be circumvented (e.g. #7109, #7153, #7546, #7834, #8109).
// So we now use microtasks everywhere, again.
// A major drawback of this tradeoff is that there are some scenarios
// where microtasks have too high a priority and fire in between supposedly
// sequential events (e.g. #4521, #6690, which have workarounds)
// or even between bubbling of the same event (#6566).
let timerFunc
//优雅降级
// The nextTick behavior leverages the microtask queue, which can be accessed
// via either native Promise.then or MutationObserver.
// MutationObserver has wider support, however it is seriously bugged in
// UIWebView in iOS >= 9.3.3 when triggered in touch event handlers. It
// completely stops working after triggering a few times... so, if native
// Promise is available, we will use it:
/* istanbul ignore next, $flow-disable-line */
if (typeof Promise !== 'undefined' && isNative(Promise)) {//首先,判断是否原生支持Promiseconst p = Promise.resolve()timerFunc = () => {p.then(flushCallbacks)// In problematic UIWebViews, Promise.then doesn't completely break, but// it can get stuck in a weird state where callbacks are pushed into the// microtask queue but the queue isn't being flushed, until the browser// needs to do some other work, e.g. handle a timer. Therefore we can// "force" the microtask queue to be flushed by adding an empty timer.if (isIOS) setTimeout(noop)}isUsingMicroTask = true
} else if (//其次 判断是否原生支持MutationObserver!isIE &&typeof MutationObserver !== 'undefined' &&(isNative(MutationObserver) ||// PhantomJS and iOS 7.xMutationObserver.toString() === '[object MutationObserverConstructor]')
) {// Use MutationObserver where native Promise is not available,// e.g. PhantomJS, iOS7, Android 4.4// (#6466 MutationObserver is unreliable in IE11)let counter = 1const observer = new MutationObserver(flushCallbacks)const textNode = document.createTextNode(String(counter))observer.observe(textNode, {characterData: true})timerFunc = () => {counter = (counter + 1) % 2textNode.data = String(counter)}isUsingMicroTask = true
} else if (typeof setImmediate !== 'undefined' && isNative(setImmediate)) {// 再次 判断是否原生支持setImmediate // Fallback to setImmediate.// Technically it leverages the (macro) task queue,// but it is still a better choice than setTimeout.timerFunc = () => {setImmediate(flushCallbacks)}
} else {// 最后 都不支持的情况下 则使用setTimeout来兜底// Fallback to setTimeout.timerFunc = () => {setTimeout(flushCallbacks, 0)}
}// 将回调函数cb包装成一个箭头函数push到事件队列callbacks中
export function nextTick(): Promise<void>
export function nextTick<T>(this: T, cb: (this: T, ...args: any[]) => any): void
export function nextTick<T>(cb: (this: T, ...args: any[]) => any, ctx: T): void
/*** @internal*/
export function nextTick(cb?: (...args: any[]) => any, ctx?: object) {let _resolvecallbacks.push(() => {if (cb) {try {cb.call(ctx)} catch (e: any) {handleError(e, ctx, 'nextTick')}} else if (_resolve) {_resolve(ctx)}})if (!pending) {pending = truetimerFunc()}// $flow-disable-lineif (!cb && typeof Promise !== 'undefined') {return new Promise(resolve => {_resolve = resolve})}
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/816603.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

软考中级工程师网络技术第二节网络体系结构

OSPF将路由器连接的物理网络划分为以下4种类型&#xff0c;以太网属于&#xff08;25&#xff09;&#xff0c;X.25分组交换网属于&#xff08;非广播多址网络NBMA&#xff09;。 A 点对点网络 B 广播多址网络 C 点到多点网络 D 非广播多址网络 试题答案 正确答案&#xff1a; …

【鸿蒙开发】第二十一章 Media媒体服务(二)--- 音频播放和录制

1 AVPlayer音频播放 使用AVPlayer可以实现端到端播放原始媒体资源&#xff0c;本开发指导将以完整地播放一首音乐作为示例&#xff0c;向开发者讲解AVPlayer音频播放相关功能。 以下指导仅介绍如何实现媒体资源播放&#xff0c;如果要实现后台播放或熄屏播放&#xff0c;需要…

Java使用OpenOffice将office文件转换为PDF

Java使用OpenOffice将office文件转换为PDF 1. 先行工作1.1 OpenOffice官网下载1.2 JODConverter官网下载1.3 下载内容 2.介绍3. 安装OpenOffice服务3.1.Windows环境3.2 Linux环境 4. maven依赖5. 转换代码 1. 先行工作 请注意&#xff0c;无论是windows还是liunx环境都需要安装…

Flutter - iOS 开发者速成篇

首先 安装FLutter开发环境&#xff1a;M1 Flutter SDK的安装和环境配置 然后了解Flutter和Dart 开源电子书&#xff1a;Flutter实战 将第一章初略看一下&#xff0c;你就大概了解一下Flutter和Dart这门语言 开始学习Dart语言 作为有iOS经验的兄弟们&#xff0c;学习Dart最快…

C# dynamic 数据类型

在C#中&#xff0c;dynamic是一种数据类型&#xff0c;它允许在运行时推迟类型检查和绑定。使用dynamic类型&#xff0c;可以编写更具灵活性的代码&#xff0c;因为它允许在编译时不指定变量的类型&#xff0c;而是在运行时根据实际情况进行解析。 dynamic类型的变量可以存储任…

【脚本】多功能Ubuntu临时授予用户sudo权限管理工具

转载请注明出处&#xff1a;小锋学长生活大爆炸[xfxuezhagn.cn] 设计原理和初衷可以看这里&#xff1a;【技巧】Ubuntu临时授予用户sudo权限&#xff0c;并在一定时间后自动撤销_ubuntu jianshao sudo-CSDN博客文章浏览阅读404次。非常实用_ubuntu jianshao sudohttps://blog.c…

Spring Boot 经典面试题(八)

1.SpringBoot微服务中如何实现 session 共享 在Spring Boot微服务中实现session共享可以通过不同的方式&#xff0c;取决于你的微服务架构和需求。下面列出了一些常见的方法&#xff1a; 使用Spring Session和Redis&#xff1a; 配置Spring Session来将session数据存储在Redis…

2.2 算法之 前缀和

学习笔记参考&#xff1a;https://leetcode.cn/leetbook/read/qian-zhui-he/nk1f5i/ 一维前缀和 前缀和是算法题中一个重要的技巧&#xff0c;经常作为一种优化方式出现在其他算法的一些子环节中。本课程就来带着同学们整理与巩固前缀和相关知识点&#xff0c;在学习完本课程之…

SpringBoot+FreeMaker

目录 1.FreeMarker说明2.SpringBootFreeMarker快速搭建Pom文件application.properties文件Controller文件目录结构 3.FreeMarker数据类型3.1.布尔类型3.2.数值类型3.3.字符串类型3.4.日期类型3.5.空值类型3.6.sequence类型3.7.hash类型 4.FreeMarker指令assign自定义变量指令if…

C++版【AVL树的模拟实现】

前言 在学习AVL树的底层之前&#xff0c;先回顾一下二叉搜索树&#xff0c;我们知道二叉搜索树在极端场景是会形成单支树的&#xff0c;如下图&#xff1a; 在退化成单支树后&#xff0c;查找的效率就会降到O(n)&#xff0c;所以为了解决退化成单支树的情况&#xff0c;AVL树就…

stm32移植嵌入式数据库FlashDB

本次实验的程序链接stm32f103FlashDB嵌入式数据库程序资源-CSDN文库 一、介绍 FlashDB 是一款超轻量级的嵌入式数据库&#xff0c;专注于提供嵌入式产品的数据存储方案。与传统的基于文件系统的数据库不同&#xff0c;FlashDB 结合了 Flash 的特性&#xff0c;具有较强的性能…

Ubuntu20.04安装FloodLight最新版本

Ubuntu20.04安装FloodLight最新版本 网上的很多教程尝试了一下都不对&#xff0c;并且很多都是基于Ubuntu14的旧版本系统&#xff0c;其中的Python环境大多是基于2.0的&#xff0c;由于本人所使用的系统是Ubuntu20.04&#xff0c;后再油管澳大利亚某个学校的网络教学视频的帮助…

【Vue】面试题

vue的组建通信方式 父子关系&#xff1a;props & $emit 、 $parent / $children 、 ref / $refs 、 插槽跨层级关系&#xff1a; provide & inject通用方案&#xff1a;Vuex 或 eventbus 插播&#xff1a;兄弟组建怎么通信&#xff1f; eventbusVuex通过中间件&…

架构师系列-搜索引擎ElasticSearch(六)- 映射

映射配置 在创建索引时&#xff0c;可以预先定义字段的类型&#xff08;映射类型&#xff09;及相关属性。 数据库建表的时候&#xff0c;我们DDL依据一般都会指定每个字段的存储类型&#xff0c;例如&#xff1a;varchar、int、datetime等&#xff0c;目的很明确&#xff0c;就…

getLocation需要在app.json中声 明permission字段

这是我在使用微信小程序的时候 获取本机地址的时候会出现的这个问题 这个问题很好解决 获取本地定位的代码也很简单 wx.getLocation({// 国内只能使用gcj02坐标系&#xff0c;wgs84不能使用&#xff1b;高德地图等都是使用的gcj02type: "gcj02",success: function (…

STM32之DHT11温湿度传感器

目录 一 DHT11温湿度传感器简介 1.1 传感器特点 1.2 传感器特性 1.3 传感器引脚说明 二 测量原理及方法 2.1 典型应用电路 2.2 单线制串行简介 2.2.1 串行接口 (单线双向) 2.2.2 数据示例 2.3 通信时序 三 单片机简介 3.1 STM32F103C8T6最小系统板 四 接线说明 …

011、Python+fastapi,第一个后台管理项目走向第11步:建立python+fastapi项目,简单测试一下

一、说明 本文章就是记录自己的学习过程&#xff0c;如果有用您可以参考&#xff0c;没用你就略过&#xff0c;没有好与不好之分&#xff0c;今天主要是参考了gitee上的一些项目&#xff0c;一步一步的往后i建立 对于学习来说&#xff0c;如果您有java c等经验&#xff0c;py…

wpf下RTSP|RTMP播放器两种渲染模式实现

技术背景 在这篇blog之前&#xff0c;我提到了wpf下播放RTMP和RTSP渲染的两种方式&#xff0c;一种是通过控件模式&#xff0c;另外一种是直接原生RTSP、RTMP播放模块&#xff0c;回调rgb&#xff0c;然后在wpf下渲染&#xff0c;本文就两种方式做个说明。 技术实现 以大牛直…

云轴科技ZStack支持国家地震烈度速报与预警工程实现秒级地震预警能力

编者按&#xff1a;巨灾项目&#xff0c;作为国家公共安全体系的重要组成部分&#xff0c;对于提升我国防灾减灾能力具有举足轻重的意义。其中&#xff0c;地震预警作为巨灾项目的重要一环&#xff0c;其技术的创新与应用直接关系到人民群众的生命财产安全。云轴科技ZStack在国…

vite配置eslint24年4月期,eslint.config.js

一、背景 最新版的eslint&#xff0c;默认init之后为eslint.config.js&#xff0c;整体配置较之前版本均有变动&#xff1b; vite&ts版本。 1.1 安装 pnpm i eslint -D1.2 初始化 npx eslint --init npx eslint --init Need to install the following packages:eslint/…