vue nextTick实现原理

568 阅读2分钟

问题

<div id="app">
    <p ref="ref" v-if="isShow">{{ message }}</p>
    <button @click="getWidth">获取p元素宽度</button>
</div>

<script>
    export default {
        data() {
            return {
                isShow: false,
                message: 0
            }
        },
        methods: {
            getWidth() {
                this.isShow = isShow;
                this.message = this.$ref.ref.offsetWidth;
            }
        }
        
    }
</script>

我们来看上述代码会有什么问题,当点击按钮的时候将p标签显示出来,然后获取宽度显示到页面上。事实上,在赋值完之后立即取this.$ref.ref的时候是取不到的,所以再点击按钮的时候会报错。

原因

Vue 在更新 DOM 时是异步执行的。只要侦听到数据变化,Vue 将开启一个队列,并缓冲在同一事件循环中发生的所有数据变更。在上述代码中,我们在更新数据后立即取最新的DOM节点是取不到的,此时他并未被更新到DOM结构中。

解决方案

Vue提供了nextTick的方法,在修改数据之后立即使用这个方法,获取更新后的 DOM。

官方解释:

Vue.nextTick( [callback, context] )

  • 参数

    • {Function} [callback]
    • {Object} [context]
  • 用法

    在下次 DOM 更新循环结束之后执行延迟回调。在修改数据之后立即使用这个方法,获取更新后的 DOM。

    // 修改数据
    vm.msg = 'Hello'
    // DOM 还没有更新
    Vue.nextTick(function () {
      // DOM 更新了
    })
    
    // 作为一个 Promise 使用 (2.1.0 起新增,详见接下来的提示)
    Vue.nextTick()
      .then(function () {
        // DOM 更新了
      })
    

所以我们修改之前的代码如下

getWidth() {
    this.isShow = isShow;
    this.nextTick(() => {
        this.message = this.$ref.ref.offsetWidth;
    })
}

这样就可以获取更新后的DOM了。

nextTick源码

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)
    }
  })
  if (!pending) {
    pending = true
    timerFunc()
  }
  // $flow-disable-line
  if (!cb && typeof Promise !== 'undefined') {
    return new Promise(resolve => {
      _resolve = resolve
    })
  }
}

上述代码就是Vue中nextTick的实现,我们来分析下代码.

他会将传入的回调函数方法哦callbacks数组中,然后调用timerFunc方法,我们来看下timerFunc函数

if (typeof Promise !== 'undefined' && isNative(Promise)) {
  const 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 (!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.
  // 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)
  }
}

这段代码针对浏览器兼容问题一步步降级处理,其中我们发现一个flushCallbacks,我们来看下这段代码

function flushCallbacks () {
  pending = false
  const copies = callbacks.slice(0)
  callbacks.length = 0
  for (let i = 0; i < copies.length; i++) {
    copies[i]()
  }
}

这个函数的作用就是复制一份callbacks数组,然后依次执行callbacks里面存的函数。