vue的nexttick源码分析

源码地址:https://github.com/vuejs/vue

模块路径:src\core\util\next-tick.js

问题:vue中的数据和界面更新是异步的,所以数据更新后dom不能立刻更新,那么想要获取到最新的dom数据,就需要nextTick帮我们实现

分析:

  1. 如果支持promise,则首先以promise的方式执行,但是界面更新是在微任务之后执行,所以用promise拿到的数据不是从界面获取的,而是从dom树上获取的,IOS的UIWebViews不支持promise
  2. 否则,如果不是IE浏览器并且支持MutationObserver,则以MutationObserver的方式执行,MutationObserver的作用是监听dom变化,dom更新后执行回调。MutationObserver在IE浏览器中会出现问题,所以在IE中不用这个API

  3. 否则,如果支持setImmediate,则使用setImmediate,setImmediate与setTimeout比起来效率更高,setImmediate会立即执行,没有延迟

  4. 否则以setTimeout(下下策)

核心代码: 

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) ||
  MutationObserver.toString() === '[object MutationObserverConstructor]'
)) {
  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)) {
  timerFunc = () => {
    setImmediate(flushCallbacks)
  }
} else {
  timerFunc = () => {
    setTimeout(flushCallbacks, 0)
  }
}

全部代码: 

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

export let isUsingMicroTask = false

const callbacks = []
let pending = false

function flushCallbacks () {
  pending = false
  const copies = callbacks.slice(0)//备份一份
  callbacks.length = 0
  for (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 */

// 优先以promise处理,promise执行的时候界面还没有更新,数据更新后watcher会立即更新dom树
// 所以此时是从dom树上获取的最新数据(同步任务->微任务->更新界面->宏任务)
if (typeof Promise !== 'undefined' && isNative(Promise)) {
  const p = Promise.resolve()
  timerFunc = () => {
    p.then(flushCallbacks)//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.
    // IOS的UIWebViews控件不支持promise
    if (isIOS) setTimeout(noop)
  }
  isUsingMicroTask = true
  // MutationObserver的作用是监听dom对象的改变,改变后会执行一个回调函数,也是个微任务(在IE11中有问题)
} 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
  // 否则降级为setImmediate,setImmediate只有IE浏览器和Node支持
  // 好处是setImmediate性能比setTimeout好,setTimeout设为0也需要等4ms,setImmediate会立即执行
} else if (typeof setImmediate !== 'undefined' && isNative(setImmediate)) {
  // Fallback to setImmediate.
  // Technically 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)
  }
}
// cb是用户传过来的
export function nextTick (cb?: Function, ctx?: Object) {
  let _resolve
  callbacks.push(() => {//存储回调函数cb
    if (cb) {
      try {
        cb.call(ctx)
      } catch (e) {
        handleError(e, ctx, 'nextTick')
      }
    } else if (_resolve) {
      _resolve(ctx)
    }
  })
  if (!pending) {//队列是否正在被处理
    pending = true
    timerFunc()//遍历callback数组,依次调用,重点!!!!
  }
  // $flow-disable-line
  if (!cb && typeof Promise !== 'undefined') {
    // 返回promise对象
    return new Promise(resolve => {
      _resolve = resolve
    })
  }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值