vue.$nextTick浅析

$nextTick用于在数据更新和DOM渲染后执行回调,确保能获取到最新的DOM状态。它在DOM更新的异步队列中工作,可以解决因DOM未及时更新导致的问题。文章通过示例解释了$nextTick在创建周期、数据变更和DOM操作中的使用,并探讨了其源码实现,包括Promise和MutationObserver的使用情况。
摘要由CSDN通过智能技术生成

$nextTick调用时机以及作用

当数据更新并在dom中渲染后,会自动调用执行,简单来说就是获取更新之后的dom

由于vue响应式不是数据改变dom立即改变,所以未使用$nextTick之前立即去获取dom数据,得到的是改变之前的数据

示例

<template>
    <div>
        <div @click='changeMsg' ref="btnone">{{msg1}}</div>
        <div @click='changeMsg' ref="btntwo">{{msg2}}</div>
    </div>
</template>
<script>
export default{
    data(){
         return{
            msg1:'hello',
            msg2:'hello word'
         }
    },
    methods:{
        changeMsg(){
            this.msg1 = 'hello1'
            this.msg2 = 'hello1 word'
            console.log(this.$refs.btnone.innerText);    // hello
            this.$nextTick(()=>{
                console.log(this.$refs.btntwo.innerText);    // hello1 word
            })
        }
    }
}
</script>

应用场景

在vue生命周期create()函数中进行dom操作

原因:在create()函数执行的时候,dom没有渲染,这个时候进行dom操作会报错,所以一定要将操作dom的动作也就是js代码放在$nextTick的回调函数中

<template>
    <div>
        <div @click='changeMsg' ref="btnone">{{msg1}}</div>
        <div @click='changeMsg' ref="btntwo">{{msg2}}</div>
    </div>
</template>
<script>
export default{
    data(){
         return{
            msg1:'hello',
            msg2:'hello word'
         }
    },
    created(){
        console.log(this.$refs.btnone.innerText);    // 报错 Error in created hook: "TypeError: Cannot read properties of undefined (reading 'innerText')
        this.$nextTick(()=>{
            console.log(this.$refs.btntwo.innerText);    // hello word
        })
    }
}
</script>

在数据变化后立即执行的某个操作,而这个操作需要用到随数据改变而改变的dom结构

原因:vue异步执行dom更新,只要观察到数据变化,vue将开启一个队列,并缓存在同一事件中的所有数据改变,如果同一个watch被多次触发,只会记录最后一次。然后再下一个事件循环中,vue刷新队列并执行已去重的工作,vue 在内部尝试对异步队列使用原生的 promise.then和MessageChannel,如果执行环境不支持,会采用 setTimeout代替。

例如,当你设置vm.data = 'new value',该组件不会立即重新渲染。当刷新队列时,组件会在事件循环队列清空时的下一个“tick”更新。为了在数据变化之后等待 Vue 完成更新 DOM ,可以在数据变化之后立即使用Vue.nextTick(callback) 。这样回调函数在 DOM 更新完成后就会调用。

<template>
    <div>
        <h1 ref="hbox" style="white-space: pre-wrap;">{{hmsg}}</h1>
        <button @click='changeMsg'>点击加一行</button>
    </div>
</template>

<script>
    import {
        nextTick
    } from "vue";
    export default {
        data() {
            return {
                hmsg: '',
            }
        },
        methods: {
            changeMsg() {
                this.hmsg += '我是标题\n'
                console.log(this.$refs.hbox.offsetHeight);    // 0
                this.$nextTick(()=>{
                    console.log(this.$refs.hbox.offsetHeight);    // 42
                })
            }
        }
    }
</script>

nextTick源码浅析

使用方法

nextTick用于延迟执行一段代码,接收两个参数:回调函数和执行回调函数的上下文环境,如果没有提供回调函数,将返回一个promise对象

源码

/**
 * 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
      })
    }
  }
})()

粗浅解析

三个变量
  • callbacks:存储所有需要执行的回调函数

  • pending:判断是否有正在执行的回调函数

  • timerFunc:触发执行回调函数

nextTickHandler函数

用来执行callbacks里存储的所有回调函数,并将触发方式赋值给timerFunc

timerFunc函数
  • 判断是否支持promise,如果支持则利用promise来执行回调函数;

  • 如果支持MutationObserver,则实例化一个观察者对象,文本节点发生变化时,执行回调函数。

  • 如果都不支持,则利用setTimeout并且设置延时为0。

queueNextTick函数

因为nextTick是一个即时函数,所以用queueNextTick函数接受用户传入的参数,然后往callbacks里存入回调函数。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值