nextTick研究报告

BLOG传送门

  • nextTick
    • es5源码
    • 关于setTimeout(fn,0)
  • 讨论点
  • 常用示例
    • 1.mounted时更新
      • console
    • 2.更改子组件更新时间
      • console
    • 3.同时更改父组件更新时间
      • console
    • 4.nextTick顺序问题
      • console
  • 总结

nextTick

在下次 DOM 更新循环结束之后执行延迟回调。在修改数据之后立即使用这个方法,获取更新后的 DOM。

vue这么做是因为频繁的更新dom是特别耗费性能的,所以搞了一个批处理更新,把所有的update操作放到任务队列中,等主线程中执行栈的所有同步任务执行完毕,系统就会读取任务队列。

es5源码

/**
 * Defer a task to execute it asynchronously.
 * 异步更新队列
 */
var nextTick = (function() {
    var callbacks = [];
    var pending = false;
    var timerFunc;

    function nextTickHandler() {
        pending = false;

        var copies = callbacks.slice(0);
        callbacks.length = 0;
        for (var i = 0; i < copies.length; i++) {
            copies[i]();
        }
    }

    // 只要观察到数据变化,Vue 将开启一个队列,并缓冲在同一事件循环中发生的所有数据改变。
    // 如果同一个 watcher 被多次触发,只会被推入到队列中一次。
    // 这种在缓冲时去除重复数据对于避免不必要的计算和 DOM 操作上非常重要。
    // 然后,在下一个的事件循环“tick”中,Vue 刷新队列并执行实际 (已去重的) 工作。
    // Vue 在内部尝试对异步队列使用原生的 Promise.then 和 MessageChannel,如果执行环境不支持,会采用 setTimeout(fn, 0) 代替。
    timerFunc = function() {
        setTimeout(nextTickHandler, 0);
    };

    return function queueNextTick(cb, ctx) {
        var _resolve;
        callbacks.push(function() {
            if (cb) {
                try {
                    cb.call(ctx);
                } catch (e) {
                    handleError(e, ctx, 'nextTick');
                }
            } else if (_resolve) {
                _resolve(ctx);
            }
        });
        if (!pending) {
            pending = true;
            timerFunc();
        }
    }
})();

Vue.prototype.$nextTick = function(fn) {
    return nextTick(fn, this)
};

关于setTimeout(fn,0)

理解 JavaScript 中的 macrotask 和 microtask

JavaScript 主线程拥有一个 执行栈 以及一个 任务队列,主线程会依次执行代码,当遇到函数时,会先将函数 入栈,函数运行完毕后再将该函数 出栈,直到所有代码执行完毕。

  • macrotasks: setTimeout, setInterval, setImmediate, I/O, UI rendering
  • microtasks: process.nextTick, Promises, Object.observe(废弃), MutationObserver

在每一次事件循环中,macrotask 只会提取一个执行,而 microtask 会一直提取,直到 microtasks 队列清空。

讨论点

  • 父组件nextTick的触发在子组件DOM完成前还是完成后?

常用示例

codepen示例

  • DOM
<div id="J_app">
    <h3>{{title}}</h3>
    <item></item>
</div>

1.mounted时更新

  • 父组件
(function() {
    var app = new Vue({
        el: "#J_app",
        data: {
            title: "父组件"
        },

        beforeCreate: function() { // 实例初始化之后
            console.log("父组件beforeCreate");
        },
        created: function() { // 实例创建完成之后被调用
            console.log("父组件created");
        },

        beforeMount: function() { // 在挂载开始之前被调用
            console.log("父组件beforeMount");
        },

        beforeUpdate: function() { // 数据更新时调用
            console.log("父组件beforeUpdate");
        },

        updated: function() { // 数据更新之后调用
            console.log("父组件updated");
        },

        mounted: function() { // el被新创建的vm.$el替换,挂载到实例上
            var that = this;

            console.log("父组件mounted");

            this.$nextTick(function() {
                console.log("父组件nextTick");
                console.log("当前页面content:" + that.$el.textContent);

            });

            that.title = "父组件更新";
            console.log("父组件更新");
            console.log("当前页面content:" + that.$el.textContent);
        }
    });
})();
  • 子组件
(function() {
    var tpl = "<h4>{{subtitle}}</h4>";

    Vue.component('item', {
        data: function() {
            return {
                subtitle: "子组件"
            }
        },
        props: [],
        template: tpl,
        beforeCreate: function() { // 实例初始化之后
            console.log("子组件beforeCreate");
        },
        created: function() { // 实例创建完成之后被调用
            console.log("子组件created");
        },

        beforeMount: function() { // 在挂载开始之前被调用
            console.log("子组件beforeMount");
        },

        beforeUpdate: function() { // 数据更新时调用
            console.log("子组件beforeUpdate");
        },

        updated: function() { // 数据更新之后调用
            console.log("子组件updated");
        },
        mounted: function() { // el被新创建的vm.$el替换,挂载到实例上
            var that = this;

            console.log("子组件mounted")

            this.$nextTick(function() {
                console.log("子组件nextTick");
                console.log("当前页面content:" + that.$el.textContent);
            });

            that.subtitle = "子组件更新";
            console.log("子组件更新");
            console.log("当前页面content:" + that.$el.textContent);
        }
    });
})();

console

父组件beforeCreate
父组件created
父组件beforeMount
子组件beforeCreate
子组件created
子组件beforeMount
子组件mounted
子组件更新
当前页面content:子组件
父组件mounted
父组件更新
当前页面content:父组件 子组件
子组件nextTick
当前页面content:子组件
父组件beforeUpdate
子组件beforeUpdate
子组件updated
父组件updated
父组件nextTick
当前页面content:父组件更新 子组件更新
image

nextTick写在数据更改前不能拿到更新后的数据。

2.更改子组件更新时间

(function() {
    var tpl = "<h4>{{subtitle}}</h4>";

    Vue.component('item', {
        data: function() {
            return {
                subtitle: "子组件"
            }
        },
        props: [],
        template: tpl,
        beforeCreate: function() { // 实例初始化之后
            console.log("子组件beforeCreate");
        },
        created: function() { // 实例创建完成之后被调用
            console.log("子组件created");
        },

        beforeMount: function() { // 在挂载开始之前被调用
            console.log("子组件beforeMount");
        },

        beforeUpdate: function() { // 数据更新时调用
            console.log("子组件beforeUpdate");
        },

        updated: function() { // 数据更新之后调用
            console.log("子组件updated");
        },
        mounted: function() { // el被新创建的vm.$el替换,挂载到实例上
            var that = this;

            console.log("子组件mounted")

            this.$nextTick(function() {
                console.log("子组件nextTick");
                console.log("当前页面content:" + that.$el.textContent);
            });

            setTimeout(function() {
                that.subtitle = "子组件更新";
                console.log("子组件更新");
                console.log("当前页面content:" + that.$el.textContent);
            }, 1000);
        }
    });
})();

console

父组件beforeCreate
父组件created
父组件beforeMount
子组件beforeCreate
子组件created
子组件beforeMount
子组件mounted
父组件mounted
父组件更新
当前页面content:父组件 子组件
子组件nextTick
当前页面content:子组件
父组件nextTick
当前页面content:父组件 子组件
父组件beforeUpdate
父组件updated

子组件更新
当前页面content:子组件
子组件beforeUpdate
子组件updated
image

若子组件在mounted即更新,子组件的update动作会在父组件的beforeUpdate之后updated之前执行。
反之则更新后子组件自己执行update,并且由于父组件nextTick写在数据更改之前,导致先执行父组件nextTick再执行父组件的update动作。

3.同时更改父组件更新时间

(function() {
    var app = new Vue({
        el: "#J_app",
        data: {
            title: "父组件"
        },

        beforeCreate: function() { // 实例初始化之后
            console.log("父组件beforeCreate");
        },
        created: function() { // 实例创建完成之后被调用
            console.log("父组件created");
        },

        beforeMount: function() { // 在挂载开始之前被调用
            console.log("父组件beforeMount");
        },

        beforeUpdate: function() { // 数据更新时调用
            console.log("父组件beforeUpdate");
        },

        updated: function() { // 数据更新之后调用
            console.log("父组件updated");
        },

        mounted: function() { // el被新创建的vm.$el替换,挂载到实例上
            var that = this;

            console.log("父组件mounted");

            this.$nextTick(function() {
                console.log("父组件nextTick");
                console.log("当前页面content:" + that.$el.textContent);

            });

            setTimeout(function() {
                that.title = "父组件更新";
                console.log("父组件更新");
                console.log("当前页面content:" + that.$el.textContent);
            }, 1000);
        }
    });
})();

console

父组件beforeCreate
父组件created
父组件beforeMount
子组件beforeCreate
子组件created
子组件beforeMount
子组件mounted
父组件mounted
子组件nextTick
当前页面content:子组件
父组件nextTick
当前页面content:父组件 子组件

子组件更新
当前页面content:子组件
子组件beforeUpdate
子组件updated
父组件更新
当前页面content:父组件 子组件更新
父组件beforeUpdate
父组件updated
image

若父、子组件的更新延时相同,则会各自执行各自的update动作,子组件优先。

4.nextTick顺序问题

nextTick应写在数据更改后

  • 父组件
(function() {
    var app = new Vue({
        el: "#J_app",
        data: {
            title: "父组件"
        },

        beforeCreate: function() { // 实例初始化之后
            console.log("父组件beforeCreate");
        },
        created: function() { // 实例创建完成之后被调用
            console.log("父组件created");
        },

        beforeMount: function() { // 在挂载开始之前被调用
            console.log("父组件beforeMount");
        },

        beforeUpdate: function() { // 数据更新时调用
            console.log("父组件beforeUpdate");
        },

        updated: function() { // 数据更新之后调用
            console.log("父组件updated");
        },

        mounted: function() { // el被新创建的vm.$el替换,挂载到实例上
            var that = this;

            console.log("父组件mounted");

            that.title = "父组件更新";
            console.log("父组件已更新");
            console.log("当前页面content:" + that.$el.textContent);

            this.$nextTick(function() {
                console.log("父组件nextTick");
                console.log("当前页面content:" + that.$el.textContent);
            });
        }
    });
})();
  • 子组件
(function() {
    var tpl = "<h4>{{subtitle}}</h4>";

    Vue.component('item', {
        data: function() {
            return {
                subtitle: "子组件"
            }
        },
        props: [],
        template: tpl,
        beforeCreate: function() { // 实例初始化之后
            console.log("子组件beforeCreate");
        },
        created: function() { // 实例创建完成之后被调用
            console.log("子组件created");
        },

        beforeMount: function() { // 在挂载开始之前被调用
            console.log("子组件beforeMount");
        },

        beforeUpdate: function() { // 数据更新时调用
            console.log("子组件beforeUpdate");
        },

        updated: function() { // 数据更新之后调用
            console.log("子组件updated");
        },
        mounted: function() {
            var that = this;

            console.log("子组件mounted")

            that.subtitle = "子组件更新";
            console.log("子组件已更新");
            console.log("当前页面content:" + that.$el.textContent);

            this.$nextTick(function() {
                console.log("子组件nextTick");
                console.log("当前页面content:" + that.$el.textContent);
            });
        }
    });
})();

console

父组件beforeCreate
父组件created
父组件beforeMount
子组件beforeCreate
子组件created
子组件beforeMount
子组件mounted
子组件已更新
当前页面content:子组件
父组件mounted
父组件已更新
当前页面content:父组件 子组件
父组件beforeUpdate
子组件beforeUpdate
子组件updated
父组件updated
子组件nextTick
当前页面content:子组件更新
父组件nextTick
当前页面content:父组件更新 子组件更新
image

如果子组件nextTick写在数据更改前,则会在父组件mouted之后beforeUpdate之前执行nextTick。实际应在updated之后执行nextTick,这样nextTick才能拿到最新的数据。

  • 推荐在updated中执行$nextTick
updated: function() { // 数据更新之后调用
    var that = this;

    console.log("组件updated");
    this.$nextTick(function() {
        console.log("组件nextTick");
    });
}

总结

  • 父组件nextTick的触发在子组件updated后

  • 若子组件在mounted即更新,子组件的update动作会在父组件的beforeUpdate之后updated之前执行。反之则更新后子组件自己执行update,不会影响父组件的nextTick

  • 若父、子组件的更新延时相同,则会各自执行各自的update动作,子组件优先

  • nextTick都需写在各自组件的updated之后

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 216,843评论 6 502
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,538评论 3 392
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 163,187评论 0 353
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,264评论 1 292
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,289评论 6 390
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,231评论 1 299
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,116评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,945评论 0 275
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,367评论 1 313
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,581评论 2 333
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,754评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,458评论 5 344
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,068评论 3 327
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,692评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,842评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,797评论 2 369
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,654评论 2 354

推荐阅读更多精彩内容