vue视图更新原理、nextTick()原理

简介: vue视图更新原理追踪变化 当你把一个普通的 JavaScript 对象传入 Vue 实例作为 data 选项,Vue 将遍历此对象所有的属性,并使用 Object.defineProperty 把这些属性全部转为 getter/setter。

vue视图更新原理

  1. 追踪变化
    当你把一个普通的 JavaScript 对象传入 Vue 实例作为 data 选项,Vue 将遍历此对象所有的属性,并使用 Object.defineProperty 把这些属性全部转为 getter/setter。
  2. 异步更新队列
    Vue在更新DOM时是异步更新的。只要侦听到数据变化,Vue 将开启一个队列,并缓冲在同一事件循环中发生的所有数据变更。如果同一个 watcher 被多次触发,只会被推入到队列中一次。这种在缓冲时去除重复数据对于避免不必要的计算和 DOM 操作是非常重要的。然后,在下一个的事件循环“tick”中,Vue 刷新队列并执行实际 (已去重的) 工作。Vue 在内部对异步队列尝试使用原生的 Promise.then、MutationObserver 和 setImmediate,如果执行环境不支持,则会采用 setTimeout(fn, 0) 代替。

例如,当你设置 vm.someData = 'new value',该组件不会立即重新渲染。当刷新队列时,组件会在下一个事件循环“tick”中更新。多数情况我们不需要关心这个过程,但是如果你想基于更新后的 DOM 状态来做点什么,这就可能会有些棘手。虽然 Vue.js 通常鼓励开发人员使用“数据驱动”的方式思考,避免直接接触 DOM,但是有时我们必须要这么做。为了在数据变化之后等待 Vue 完成更新 DOM,可以在数据变化之后立即使用 Vue.nextTick(callback)。这样回调函数将在 DOM 更新完成后被调用。例如:

var vm = new Vue({
  el: '#example',
  data: {
    message: '123'
  }
})
vm.message = 'new message' // 更改数据
vm.$el.textContent === 'new message' // false
Vue.nextTick(function () {
  vm.$el.textContent === 'new message' // true
})

以上是官方文档解释。自己理解如下
当数据发生改变,vue将开启一个异步队列,这个异步队列包括Promise.thenMutationObserversetImmediatesetTimeout(fn, 0),vue会自动判断当前环境支持哪个异步事件,按顺序依次使用对应的异步api.

事件循环:分为微任务队列、宏任务队列。
微任务队列:Promise、process.nextTick, Promises, Object.observe, MutationObserver
宏任务队列: script(整体代码),setTimeout, setInterval, setImmediate, I/O, UI rendering

this.msgtest = '222'
this.$nextTick(() => {
    console.log(this.$refs.msg.innerText)
})
this.msg = 'xinde'

如上代码:当改变this.msgtest的值时,就会开启一个异步队列(Promise),在相同一个事件循环中再次改变this.msg则不会新开启异步队列,而是把msg的回调放入刚才开启的异步队列里。在上面代码里,先开启了异步队列,又添加了nextTick事件,nextTick事件同样也会开启异步队列,这样nextTick的异步队列就会后执行,这时候就会获取到msg最新的值

this.$nextTick(() => {
   console.log(this.$refs.msg.innerText)
})
this.msg = 'xinde'

再看这个代码:此时先执行nextTick开启异步队列tick1,然后再执行this.msg开启更新dom异步队列tick2,tick1先于tick2注册,则tick1会先执行,所以nextTick的回调函数内就拿不到msg 的最新值。这就需要我们在用nextTick的时候需要放到所以数据操作之后的位置,保证异步队列的执行顺序

nextTick()原理

源码

/**
 * Defer a task to execute it asynchronously.
 */
export const nextTick = (function () {
  const callbacks = []
  let pending = false
  let timerFunc

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

  // 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 if */
  if (typeof Promise !== 'undefined' && isNative(Promise)) {
    var p = Promise.resolve()
    var logError = err => { console.error(err) }
    timerFunc = () => {
      p.then(nextTickHandler).catch(logError)
      // 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)
    }
  } 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
    var counter = 1
    var observer = new MutationObserver(nextTickHandler)
    var textNode = document.createTextNode(String(counter))
    observer.observe(textNode, {
      characterData: true
    })
    timerFunc = () => {
      counter = (counter + 1) % 2
      textNode.data = String(counter)
    }
  } else {
    // fallback to setTimeout
    /* istanbul ignore next */
    timerFunc = () => {
      setTimeout(nextTickHandler, 0)
    }
  }

  return function queueNextTick (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()
    }
    if (!cb && typeof Promise !== 'undefined') {
      return new Promise((resolve, reject) => {
        _resolve = resolve
      })
    }
  }
})()

简单解释:nextTick函数是一个自运行函数,直接返回queueNextTick方法,该方法将传进来的回调函数推入callbacks中,然后直接执行timerFunc()。timerFunc()可以开启一个异步队列,而异步队列的回调函数是nextTickHandler,该函数会把callbacks里的回调函数全部执行。关键是tiemrFunc开启的异步队列,所已nextTick中的回调函数会在异步事件调用后执行。结合上一节所讲,这样就能够获取dom最新的值

相关文章
|
1天前
|
数据采集 JavaScript 前端开发
Vue框架的优缺点是什么
【7月更文挑战第5天】 Vue框架:组件化开发利于重用与扩展,响应式数据绑定简化状态管理;学习曲线平缓,生态系统丰富,集成便捷,且具性能优化手段。缺点包括社区规模相对小,类型支持不足(Vue 3.x改善),路由和状态管理需额外配置,SEO支持有限。随着发展,部分缺点正被克服。
7 1
|
1天前
|
JavaScript
Vue卸载eslint的写法,单独安装eslint,单独卸载eslint
Vue卸载eslint的写法,单独安装eslint,单独卸载eslint
|
1天前
|
JavaScript
青戈大佬安装Vue,无Eslint安装版,vue2安装,vue2无eslint,最简单配置Vue安装资料
青戈大佬安装Vue,无Eslint安装版,vue2安装,vue2无eslint,最简单配置Vue安装资料
|
1天前
|
JavaScript
This dependency was not found:* vue/types/umd in ./src/router/index.jsTo install it, you can run
This dependency was not found:* vue/types/umd in ./src/router/index.jsTo install it, you can run
This dependency was not found:* vue/types/umd in ./src/router/index.jsTo install it, you can run
|
1天前
|
JavaScript 前端开发 开发工具
如何学习vue框架
【7月更文挑战第5天】 - 先学HTML/CSS/JS基础和前端工程化工具(npm, webpack, Git)。 - 从Vue官方文档学习基础,包括指令、组件、响应式系统。 - 深入研究Vue Router和Vuex,掌握路由管理和状态管理。 - 学习自定义指令和Mixins,优化性能技巧。 - 实战项目练习,加入Vue社区,阅读相关资源,提升技能。 - 关注Vue生态,持续实践和创新,以适应不断发展的框架。
5 0
|
JavaScript 前端开发 缓存
|
2天前
|
JavaScript 区块链
vue 自定义网页图标 favicon.ico 和 网页标题
vue 自定义网页图标 favicon.ico 和 网页标题
9 1
|
2天前
|
存储 JavaScript 数据安全/隐私保护
vue实战——登录【详解】(含自适配全屏背景,记住账号--支持多账号,显隐密码切换,登录状态保持)
vue实战——登录【详解】(含自适配全屏背景,记住账号--支持多账号,显隐密码切换,登录状态保持)
12 1
|
2天前
|
JavaScript
vue实战——404页面模板001——男女手电筒动画
vue实战——404页面模板001——男女手电筒动画
8 1
|
1天前
|
缓存 JavaScript 算法
vue 性能优化
vue 性能优化
10 0