Home  >  Article  >  Web Front-end  >  Comprehensive analysis of nextTick in vue

Comprehensive analysis of nextTick in vue

青灯夜游
青灯夜游forward
2020-11-10 18:01:522040browse

The followingVue.js tutorial column will introduce to you nextTick in vue. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to everyone.

Comprehensive analysis of nextTick in vue

#vue is a very popular framework. It combines the advantages of angular and react to form a lightweight and easy-to-use mvvm with two-way data binding features. frame. I prefer to use it. When we use vue, a method we often use is this.$nextTick. I believe you have also used it. A common scenario I use is that after obtaining data, when I need to perform the next step or other operations on the new view, I find that the DOM cannot be obtained. Because the assignment operation only completes the change of the data model and does not complete the view update. At this time we need to use the functions introduced in this chapter.

Why use nextTick

Please see the following piece of code

new Vue({
  el: '#app',
  data: {
    list: []
  },
  mounted: function () {
    this.get()
  },
  methods: {
    get: function () {
      this.$http.get('/api/article').then(function (res) {
        this.list = res.data.data.list
        // ref  list 引用了ul元素,我想把第一个li颜色变为红色
        this.$refs.list.getElementsByTagName('li')[0].style.color = 'red'
      })
    },
  }
})

After I obtain the data, I assign it to the list attribute in the data model, and then I I want to reference the ul element to find the first li and change its color to red, but in fact, this will report an error. When executing this sentence, there is no li under ul, which means that the assignment operation just performed is not currently No updates to the view layer are caused.

Therefore, in this case, vue provides us with the $nextTick method. If we want to operate on the updated view in the future, we only need to pass the function to be executed to this.$nextTick method. , vue will do this work for us.

Source code interpretation

This function is very simple, starting from line 450 of vue2.2.6 version.

First of all, does this function use a simple interest mode or is it a closure function created by something?

var callbacks = [];   // 缓存函数的数组
var pending = false;  // 是否正在执行
var timerFunc;  // 保存着要执行的函数

Firstly, some variables are defined for later use. The following is a function

function nextTickHandler () {
  pending = false;
  //  拷贝出函数数组副本
  var copies = callbacks.slice(0);
  //  把函数数组清空
  callbacks.length = 0;
  // 依次执行函数
  for (var i = 0; i < copies.length; i++) {
    copies[i]();
  }
}

This function is the function actually called in $nextTick.

Next, Vue divides into three situations to delay calling the above function, because the purpose of $nextTick is to delay the incoming function until the dom is updated before using it, so here we use js in elegant descending order. method to do this.

1. Delayed call of promise.then

if (typeof Promise !== &#39;undefined&#39; && isNative(Promise)) {
  var p = Promise.resolve();
  var logError = function (err) { console.error(err); };
  timerFunc = function () {
    p.then(nextTickHandler).catch(logError);
    if (isIOS) { setTimeout(noop); }
  };
}

If the browser supports Promise, then use Promise.then to delay the function call. The Promise.then method can Delay the function to the end of the current function call stack, that is, the function is called at the end of the function call stack. thereby achieving delay.

2. MutationObserver monitors changes

else if (typeof MutationObserver !== &#39;undefined&#39; && (
  isNative(MutationObserver) ||
  MutationObserver.toString() === &#39;[object MutationObserverConstructor]&#39;
)) {

  var counter = 1;
  var observer = new MutationObserver(nextTickHandler);
  var textNode = document.createTextNode(String(counter));
  observer.observe(textNode, {
    characterData: true
  });
  timerFunc = function () {
    counter = (counter + 1) % 2;
    textNode.data = String(counter);
  };
}

MutationObserver is a new function added by h5. Its function is to monitor changes in dom nodes and execute after all dom changes are completed. Callback.

There are several specific changes to monitor

  • childList: changes in child elements

  • attributes: changes in attributes

  • characterData: changes in node content or node text

  • subtree: changes in all subordinate nodes (including child nodes and child nodes of child nodes)

It can be seen that the above code creates a text node to change the content of the text node to trigger changes, because after we update the data model, it will cause the dom node to re-render. .

So, we added such a change listener, triggering the listener with a change in a text node, and after all dom is rendered, execute the function to achieve our delay effect.

3. setTimeout delayer

else {
    timerFunc = function () {
      setTimeout(nextTickHandler, 0);
    };
  }

Using the delay principle of setTimeout, setTimeout(func, 0) will delay the func function to the beginning of the next function call stack. That is, the function is executed after the current function is executed, thus completing the delay function.

Closure function

return function queueNextTick (cb, ctx) {
    var _resolve;
    callbacks.push(function () {
      if (cb) { cb.call(ctx); }
      if (_resolve) { _resolve(ctx); }
    });
    // 如果没有函数队列在执行才执行
    if (!pending) {
      pending = true;
      timerFunc();
    }
    // promise化
    if (!cb && typeof Promise !== &#39;undefined&#39;) {
      console.log(&#39;进来了&#39;)
      return new Promise(function (resolve) {
        _resolve = resolve;
      })
    }
  }

The return function is the closure function we actually use. Every time we add a function, we will think of callbacks. Function array is pushed onto the stack. Then monitor whether it is currently being executed, and if not, execute the function. This is easy to understand. The next if is promise.

this.$nextTick(function () {

})
// promise化
this.$nextTick().then(function () {

}.bind(this))

The second way of writing the above code is not common for us. It directly calls the $nextTick function and then writes the code in promise format. However, this needs to be manually bound in the then, and Vue does not process it internally.

Related recommendations:

2020 front-end vue interview questions summary (with answers)

vue tutorial Recommendation: The latest 5 vue.js video tutorial selections in 2020

For more programming-related knowledge, please visit: Programming Courses! !

The above is the detailed content of Comprehensive analysis of nextTick in vue. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:cnblogs.com. If there is any infringement, please contact admin@php.cn delete