美文网首页
Vue.$nextTick

Vue.$nextTick

作者: LeonLi_9ea5 | 来源:发表于2020-06-23 14:58 被阅读0次

使用场景

避免出现执行 DOM 操作时 DOM 元素尚未渲染的情况

解读源码(逐行解析)

src/core/util/next-tick.js

/* @flow */
/* globals MutationObserver */

import { noop } from 'shared/util'
import { handleError } from './error'
import { isIE, isIOS, isNative } from './env'

export let isUsingMicroTask = false

const callbacks = [] // 任务队列
let pending = false

/** 
 * 清空任务队列
 * 1. 拷贝任务队列
 * 2. 循环执行队列中的 callback 函数
 */
function flushCallbacks () {
  pending = false
  const copies = callbacks.slice(0)
  callbacks.length = 0
  for (let i = 0; i < copies.length; i++) {
    copies[i]()
  }
}

// 申明一个执行器
let timerFunc

/**
 * 给执行器赋值一个执行 flushCallbacks() 的函数,形如 () => { flushCallbacks() },目的是在下一次事件循环中
 * 执行 flushCallbacks()
 * 1. 支持 Promise 的时候,使用 Promise.then()
 * 2. 不支持原生 Promise 但支持 MutationObserver 时,使用 MutationObserver 实例对象的 DOM 变化事件回调触发
 * 3. 上面两者都不支持的情况下,降级至 setImmediate()
 * 4. 以上都不满足时,使用 setTimeout(0)
 */
if (typeof Promise !== 'undefined' && isNative(Promise)) {
  const p = Promise.resolve()
  timerFunc = () => {
    p.then(flushCallbacks)
    if (isIOS) setTimeout(noop)
  }
  isUsingMicroTask = true
} else if (!isIE && typeof MutationObserver !== 'undefined' && (
  isNative(MutationObserver) ||
  // PhantomJS and iOS 7.x
  MutationObserver.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 = 1
  const observer = new MutationObserver(flushCallbacks)
  const textNode = document.createTextNode(String(counter))
  observer.observe(textNode, {
    characterData: true
  })
  timerFunc = () => {
    counter = (counter + 1) % 2
    textNode.data = String(counter)
  }
  isUsingMicroTask = true
} else if (typeof setImmediate !== 'undefined' && isNative(setImmediate)) {
  // Fallback to setImmediate.
  // Techinically it leverages the (macro) task queue,
  // but it is still a better choice than setTimeout.
  timerFunc = () => {
    setImmediate(flushCallbacks)
  }
} else {
  // Fallback to setTimeout.
  timerFunc = () => {
    setTimeout(flushCallbacks, 0)
  }
}

/**
 * 暴露 nextTick 函数
 * cb : 回调函数
 * ctx : 上下文对象
 */
export function nextTick (cb?: Function, ctx?: Object) {
  let _resolve
  callbacks.push(() => {
    if (cb) {
      try {
        cb.call(ctx)
      } catch (e) {
        handleError(e, ctx, 'nextTick')
      }
    } else if (_resolve) {
      _resolve(ctx)
    }
  })
  // 确保每次事件循环只执行一次 timerFunc
  if (!pending) {
    pending = true
    timerFunc()
  }
  // $flow-disable-line
  if (!cb && typeof Promise !== 'undefined') {
    return new Promise(resolve => {
      _resolve = resolve
    })
  }
}

实际使用过程中,通常写法是 Vue.$nextTick ( 或vm.$nextTick

 Vue.prototype.$nextTick = function (fn: Function) {
    return nextTick(fn, this) // 这里的 this 指向的是当前 Vue 实例
 }

总结

nextTick 实际上就是把Vue.$nextTick( cb() )中的 cb 先缓存到任务队列 callbacks 中,然后执行执行器函数 timerFunc 以微任务/回调/宏任务的方式,在下一次 eventLoop 中备份执行并清空任务队列

Tips

  • 微任务队列会在当前 eventLoop 的宏任务执行完毕后执行,如 Promise.then()MutationObserver.observe()即为添加微任务队列操作
  • setImmediatesetTimeout(0) 是将回调函数添加到下一次 eventLoop 的宏任务队列
  • MutationObserver 提供了监视对DOM树所做更改的能力,new MutationObserver() 的实例会在指定的DOM发生变化时被调用。具体文档参考:MutationObserver

相关文章

  • Vue.$nextTick

    使用场景 避免出现执行 DOM 操作时 DOM 元素尚未渲染的情况 解读源码(逐行解析) src/core/uti...

  • Vue.$nextTick()

    语法 什么情况下使用? 在created钩子函数中进行的dom操作时。原因:在created中所有的dom并未渲染...

  • Vue.$nextTick用法

    vue是数据驱动视图更新,但vue数据变化后,视图不会立即更新,而是异步的过程.具体的更新时机参考主队列,异步队列...

  • 20.Vue.$nextTick

    Vue.$nextTick 当dom更新后触发,结合案例理解: 场景: 页面种有个按钮(button),一个隐藏的...

  • Vue.$nextTick()的使用

    Vue 在修改数据后,视图不会立刻更新,而是等同一事件循环中的所有数据变化完成之后,再统一进行视图更新。Vue.$...

  • vue 之 $nextTick

    一、什么是Vue.$nextTick() 官方给的解释为:在下次 DOM 更新循环结束之后执行延迟回调。在修改数据...

  • Vue.$nextTick()的理解和用法

    nextTick回顾,这一切都是为了自己不被$nextTink(() => {})所抛弃!!! vm.$nextT...

  • 107、vue中$nextTick和$forceUpdate的用

    1、$nextTick vm.$nextTick( [callback] ) this.$nextTick()将回...

  • $nextTick和$forceUpdate

    $nextTick和$forceUpdate vm.$nextTick( [callback] ) 官方解释: 将...

  • node持续辨析(1)

    (1)process.nextTick()与setImmediate(fn); process.nextTick方...

网友评论

      本文标题:Vue.$nextTick

      本文链接:https://www.haomeiwen.com/subject/wzkhfktx.html