Vue中 $nextTick() 与 Vue.nextTick() 原理及使用

简介: Vue中 $nextTick() 与 Vue.nextTick() 原理及使用
Vue.nextTick( [callback, context] )
参数:
  {Function} [callback]
  {Object} [context]
用法:在下次 DOM 更新循环结束之后执行延迟回调。在修改数据之后立即使用这个方法,获取更新后的 DOM。

1. 举例说明

<template>
  <div>
    <div ref="msg">{{msg}}</div>
    <div v-if="msg1">out $nextTick: {{msg1}}</div>
    <div v-if="msg2">in $nextTick: {{msg2}}</div>
    <div v-if="msg3">out $nextTick: {{msg3}}</div>
    <button @click="changeMsg"> changeMsg </button>
  </div>
</template>
<script>
export default {
  data(){
    return{
      msg: 'Hello Vue',
      msg1: '',
      msg2: '',
      msg3: ''
    }
  },
  methods: {
    changeMsg() {
      this.msg = "Hello world"
      this.msg1 = this.$refs.msg.innerHTML
      this.$nextTick(() => {
        this.msg2 = this.$refs.msg.innerHTML
      })
      this.msg3 = this.$refs.msg.innerHTML
    }
  }
}
</script>

点击后:

2020062310470442.png

从上图可以得知:

msg1和msg3显示的内容还是变换之前的,而msg2显示的内容是变换之后的。

其根本原因是因为Vue中DOM更新是异步的。

2. 数据变化 dom 更新与 nextTick 的原理分析

2.1 数据变化

vue 双向数据绑定依赖于ES5 的 Object.defineProperty,在数据初始化的时候,通过 Object.defineProperty 为每一个属性创建 getter 与 setter,把数据变成响应式数据。对属性值进行修改操作时,如 this.msg = Hello world,实际上会触发

setter。 

2020062310470442.png

数据改变触发 set 函数

Object.defineProperty(obj, key, {
  enumerable: true,
  configurable: true,
  // 数据修改后触发set函数 经过一系列操作 完成dom更新
  set: function reactiveSetter (newVal) {
    const value = getter ? getter.call(obj) : val
    if (getter && !setter) return
    if (setter) {
      setter.call(obj, newVal)
    } else {
      val = newVal
    }
    childOb = !shallow && observe(newVal)
    dep.notify() // 执行dep notify方法
  }
})

执行 dep.notify 方法

export default class Dep {
  constructor() {
    this.id = uid++
    this.subs = []
  }
  notify() {
    const subs = this.subs.slice()
    for (let i = 0, l = subs.length; i < l; i++) {
      // 实际上遍历执行了subs数组中元素的update方法
      subs[i].update()
    }
  }
}
当数据被引用时,如 <div>{{msg}}</div> ,会执行 get 方法,并向subs数组中添加渲染 Watcher,
当数据被改变时执行 Watcher 的 update 方法执行数据更新。
update () {
  /* istanbul ignore else */
  if (this.lazy) {
    this.dirty = true
  } else if (this.sync) {
    this.run()
  } else {
    queueWatcher(this) //执行queueWatcher
  }
}

update 方法最终执行 queueWatcher

function queueWatcher (watcher: Watcher) {
  const id = watcher.id
  if (has[id] == null) {
    has[id] = true
    if (!flushing) {
      queue.push(watcher)
    } else {
      // if already flushing, splice the watcher based on its id
      // if already past its id, it will be run next immediately.
      let i = queue.length - 1
      while (i > index && queue[i].id > watcher.id) {
        i--
      }
      queue.splice(i + 1, 0, watcher)
    }
    // queue the flush
    if (!waiting) {
      // 通过 waiting 保证 nextTick 只执行一次
      waiting = true
      // 最终 queueWatcher 方法会把 flushSchedulerQueue 传入到 nextTick 中执行
      nextTick(flushSchedulerQueue)
    }
  }
}

执行 flushSchedulerQueue 方法

function flushSchedulerQueue () {
  currentFlushTimestamp = getNow()
  flushing = true
  let watcher, id
  ...
  for (index = 0; index < queue.length; index++) {
    watcher = queue[index]
    if (watcher.before) {
      watcher.before()
    }
    id = watcher.id
    has[id] = null
    // 遍历执行渲染 watcher 的 run 方法 完成视图更新
    watcher.run()
  }
  // 重置 waiting 变量 
  resetSchedulerState()
  ...
}

也就是说当数据变化最终会把 flushSchedulerQueue 传入到 nextTick 中执行 flushSchedulerQueue 函数会遍历执行watcher.run() 方法,watcher.run() 方法最终会完成视图更新,接下来我们看关键的nextTick方法到底是啥。

2.2 nextTick

nextTick 方法会被传进来的回调 push 进 callbacks 数组,然后执行 timerFunc 方法

export function nextTick (cb?: Function, ctx?: Object) {
  let _resolve
  // push进callbacks数组
  callbacks.push(() => {
     cb.call(ctx)
  })
  if (!pending) {
    pending = true
    // 执行timerFunc方法
    timerFunc()
  }
}

timerFunc

let timerFunc
// 判断是否原生支持 Promise
if (typeof Promise !== 'undefined' && isNative(Promise)) {
  const p = Promise.resolve()
  timerFunc = () => {
    // 如果原生支持Promise 用 Promise 执行flushCallbacks
    p.then(flushCallbacks)
    if (isIOS) setTimeout(noop)
  }
  isUsingMicroTask = true
// 判断是否原生支持MutationObserver
} else if (!isIE && typeof MutationObserver !== 'undefined' && (
  isNative(MutationObserver) ||
  // PhantomJS and iOS 7.x
  MutationObserver.toString() === '[object MutationObserverConstructor]'
)) {
  let counter = 1
  // 如果原生支持MutationObserver 用MutationObserver执行flushCallbacks
  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 
} else if (typeof setImmediate !== 'undefined' && isNative(setImmediate)) {
  timerFunc = () => {
  // 如果原生支持setImmediate  用setImmediate执行flushCallbacks
    setImmediate(flushCallbacks)
  }
// 都不支持的情况下使用setTimeout 0
} else {
  timerFunc = () => {
    // 使用setTimeout执行flushCallbacks
    setTimeout(flushCallbacks, 0)
  }
}
// flushCallbacks 最终执行nextTick 方法传进来的回调函数
function flushCallbacks () {
  pending = false
  const copies = callbacks.slice(0)
  callbacks.length = 0
  for (let i = 0; i < copies.length; i++) {
    copies[i]()
  }
}

nextTick 会优先使用 microTask, 其次是 macroTask 。


也就是说 nextTick 中的任务,实际上会异步执行,nextTick(callback) 类似于 Promise.resolve().then(callback),或者setTimeout(callback, 0)。


也就是说vue的视图更新 nextTick(flushSchedulerQueue) 等同于 setTimeout(flushSchedulerQueue, 0),会异步执行flushSchedulerQueue 函数,所以我们在 this.msg = Hello world 并不会立即更新dom。


要想在 dom 更新后读取 dom 信息,我们需要在本次异步任务创建之后创建一个异步任务。

image.png

为了验证这个想法我们不用nextTick,直接用setTimeout实验一下。如下面代码,验证了我们的想法。

<template>
  <div class="box">{{msg}}</div>
</template>
<script>
export default {
  name: 'index',
  data () {
    return {
      msg: 'hello'
    }
  },
  mounted () {
    this.msg = 'world'
    let box = document.getElementsByClassName('box')[0]
    setTimeout(() => {
      console.log(box.innerHTML) // world
    })
  }
}

如果我们在数据修改前 nextTick ,那么我们添加的异步任务会在渲染的异步任务之前执行,拿不到更新后的 dom。

<template>
  <div class="box">{{msg}}</div>
</template>
<script>
export default {
  name: 'index',
  data () {
    return {
      msg: 'hello'
    }
  },
  mounted () {
    this.$nextTick(() => {
      console.log(box.innerHTML) // hello
    })
    this.msg = 'world'
    let box = document.getElementsByClassName('box')[0]
  }
}

3. 应用场景

在 Vue 生命周期的 created() 钩子函数进行的 DOM 操作一定要放在 Vue.nextTick() 的回调函数中

在 created() 钩子函数执行的时候 DOM 其实并未进行任何渲染,而此时进行 DOM 操作无异于徒劳,所以此处一定要将 DOM 操作的 js 代码放进 Vue.nextTick() 的回调函数中。与之对应的就是 mounted() 钩子函数,因为该钩子函数执行时所有的 DOM 挂载和渲染都已完成,此时在该钩子函数中进行任何DOM操作都不会有问题 。

在数据变化后要执行的某个操作,而这个操作需要使用随数据改变而改变的 DOM 结构的时候,这个操作都应该放进Vue.nextTick() 的回调函数中。

参考文章(侵删)

相关文章
|
10天前
|
JavaScript 前端开发 算法
vue渲染页面的原理
vue渲染页面的原理
|
1月前
|
移动开发 JavaScript API
Vue Router 核心原理
Vue Router 是 Vue.js 的官方路由管理器,用于实现单页面应用(SPA)的路由功能。其核心原理包括路由配置、监听浏览器事件和组件渲染等。通过定义路径与组件的映射关系,Vue Router 将用户访问的路径与对应的组件关联,支持哈希和历史模式监听 URL 变化,确保页面导航时正确渲染组件。
|
1月前
|
监控 JavaScript 前端开发
ry-vue-flowable-xg:震撼来袭!这款基于 Vue 和 Flowable 的企业级工程项目管理项目,你绝不能错过
基于 Vue 和 Flowable 的企业级工程项目管理平台,免费开源且高度定制化。它覆盖投标管理、进度控制、财务核算等全流程需求,提供流程设计、部署、监控和任务管理等功能,适用于企业办公、生产制造、金融服务等多个场景,助力企业提升效率与竞争力。
104 12
|
1月前
|
JavaScript 前端开发 开发者
Vue中的class和style绑定
在 Vue 中,class 和 style 绑定是基于数据驱动视图的强大功能。通过 class 绑定,可以动态更新元素的 class 属性,支持对象和数组语法,适用于普通元素和组件。style 绑定则允许以对象或数组形式动态设置内联样式,Vue 会根据数据变化自动更新 DOM。
|
1月前
|
JavaScript 前端开发 数据安全/隐私保护
Vue Router 简介
Vue Router 是 Vue.js 官方的路由管理库,用于构建单页面应用(SPA)。它将不同页面映射到对应组件,支持嵌套路由、路由参数和导航守卫等功能,简化复杂前端应用的开发。主要特性包括路由映射、嵌套路由、路由参数、导航守卫和路由懒加载,提升性能和开发效率。安装命令:`npm install vue-router`。
|
JavaScript 前端开发 缓存
|
3月前
|
JavaScript
vue使用iconfont图标
vue使用iconfont图标
168 1
|
2月前
|
JavaScript 安全 API
iframe嵌入页面实现免登录思路(以vue为例)
通过上述步骤,可以在Vue.js项目中通过 `iframe`实现不同应用间的免登录功能。利用Token传递和消息传递机制,可以确保安全、高效地在主应用和子应用间共享登录状态。这种方法在实际项目中具有广泛的应用前景,能够显著提升用户体验。
224 8
|
2月前
|
存储 设计模式 JavaScript
Vue 组件化开发:构建高质量应用的核心
本文深入探讨了 Vue.js 组件化开发的核心概念与最佳实践。
94 1
|
4月前
|
JavaScript 前端开发 开发者
vue 数据驱动视图
总之,Vue 数据驱动视图是一种先进的理念和技术,它为前端开发带来了巨大的便利和优势。通过理解和应用这一特性,开发者能够构建出更加动态、高效、用户体验良好的前端应用。在不断发展的前端领域中,数据驱动视图将继续发挥重要作用,推动着应用界面的不断创新和进化。
120 58

热门文章

最新文章