vue $nextTick简单实现

$nextTick 是 Vue.js 中的一个方法,用于在下次 DOM 更新循环结束之后执行延迟回调。其原理是在当前 DOM 更新循环结束之后,将回调函数推入微任务队列中,等待下一个微任务执行时调用。这样可以确保在 DOM 更新完成后执行回调,以便获取更新后的 DOM 状态。

接下来我们用简单的例子来实现$nextTick的功能: 

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>vue2 $nextTick简单实现</title>
</head>

<body>
    <div id="app"></div>
</body>

<script>
    class Vue {
        constructor(options) {
            options.created.bind(this)();

            this.$el = document.querySelector(options.el);
            options.mounted.bind(this)();
        }
        $nextTick(callback) {
            // Promise.resolve()是一个微任务,需要先执行constructor的宏任务再执行它
            return Promise.resolve().then(() => {
                callback();
            })
        }
    }

    new Vue({
        el: '#app',
        created() {
            this.$nextTick(() => {
                console.log('created nextTick:', this.$el); // created nextTick: <div id=​"app">​vue2 $nextTick原理​</div>​
            })
            console.log('created:', this.$el); // created: undefined
        },
        mounted() {
            console.log('mounted:', this.$el); // mounted: <div id=​"app">​vue2 $nextTick原理​</div>​

        }
    });

</script>

</html>

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值