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() 的回调函数中。

参考文章(侵删)

相关文章
|
2天前
|
JavaScript
vue打印v-model 的值
vue打印v-model 的值
|
2天前
|
JavaScript
Vue实战-组件通信
Vue实战-组件通信
5 0
|
2天前
|
JavaScript
Vue实战-将通用组件注册为全局组件
Vue实战-将通用组件注册为全局组件
5 0
|
3天前
|
JavaScript 前端开发
vue的论坛管理模块-文章评论02
vue的论坛管理模块-文章评论02
|
3天前
|
JavaScript Java
vue的论坛管理模块-文章查看-01
vue的论坛管理模块-文章查看-01
|
JavaScript
VUE_ 之异步更新机制nextTick
VUE_ 之异步更新机制nextTick
131 0
VUE_ 之异步更新机制nextTick
|
3天前
|
JavaScript
VUE里的find与filter使用与区别
VUE里的find与filter使用与区别
12 0
|
3天前
|
JavaScript
vue页面加载时同时请求两个接口
vue页面加载时同时请求两个接口
|
3天前
|
JavaScript
vue里样式不起作用的方法,可以通过deep穿透的方式
vue里样式不起作用的方法,可以通过deep穿透的方式
12 0
|
3天前
|
移动开发 JavaScript 应用服务中间件
vue打包部署问题
Vue项目`vue.config.js`中,`publicPath`设定为&quot;/h5/party/pc/&quot;,在线环境基于打包后的`dist`目录,而非Linux的`/root`。Nginx代理配置位于`/usr/local/nginx/nginx-1.13.7/conf`,包含两个相关配置图。
vue打包部署问题