vue学习笔记
$nextTick
js<template> <div class="home"> <span ref="title">{{name}}</span> <img alt="Vue logo" src="../assets/logo.png" /> <HelloWorld msg="Welcome to Your Vue.js App" /> </div> </template> <script> // @ is an alias to /src import HelloWorld from "@/components/HelloWorld.vue"; export default { name: "Home", data(){ return{ name:'小红' } }, components: { HelloWorld }, async mounted() { this.name='小米' console.log(3,this.$refs.title); await this.$nextTick() console.log(4,this.$refs.title); }, async created() { this.name='小猫' console.log(1,this.$refs.title); await this.$nextTick() console.log(2,this.$refs.title); } }; </script>
js<template> <div class="home"> <span ref="title">{{name}}</span> <img alt="Vue logo" src="../assets/logo.png" /> <HelloWorld msg="Welcome to Your Vue.js App" /> </div> </template> <script> // @ is an alias to /src import HelloWorld from "@/components/HelloWorld.vue"; export default { name: "Home", data(){ return{ name:'小红' } }, components: { HelloWorld }, async mounted() { // this.name='小米' // console.log(3,this.$refs.title); // await this.$nextTick() // console.log(4,this.$refs.title); console.log(1); await console.log(2) console.log(3) }, async created() { console.log(4); await console.log(5) console.log(6) // this.name='小猫' // console.log(1,this.$refs.title); // await this.$nextTick() // console.log(2,this.$refs.title); } }; </script>
实现原理
分为宏任务和微任务
- 微任务检测
Promise
不支持降级为宏任务 - 宏任务检测
setImmediate
不支持就检测MessageChannel
,最后降级为setTimeout
将callback压入callbacks数组,在下一个tick时遍历callbacks数组 这里使用 callbacks 而不是直接在 nextTick 中执行回调函数的原因是保证在同一个 tick 内多次执行 nextTick,不会开启多个异步任务,而把这些异步任务都压成一个同步任务,在下一个 tick 执行完毕。