$nextTick
1、问题
Vue 实现响应式,在 data 更新后,一定时间内,没有继续操作DOM,然后会触发浏览器渲染引擎去更新DOM,更新DOM也是需要时间的,所以 data 更新引起的 DOM更新并不是实时的。
2、$nextTick
this.$nextTick(() => {
// ...
});
- $nextTick 是在下次 DOM 更新循环结束之后执⾏延迟回调,在修改数据之后使⽤ $nextTick,则可以在回调中获取更新后的 DOM,在下次 DOM 更新循环结束之后执行延迟回调。
- 当数据更新了,在dom中渲染后,⾃动执⾏该函数。
3、应用场景
💡 Tips:显示组件,并调用组件的初始化方法
<template>
<div id="app">
<Son v-if="showSonComponent" ref="sonComponent" />
</div>
</template>
<script>
import Son from './components/SlotComponents/Son'
export default {
name: 'App',
components: { Son },
data() {
return {
showSonComponent: false
}
},
methods: {
init() {
// 更新该变量,会引起 DOM 更新
this.showSonComponent = true
this.$nextTick(() => {
// 需要等DOM更新完成后调用init方法
this.$refs.sonComponent.init()
})
}
}
}
</script>
<style>
#app {
font-family: Avenir, Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
background: #4a90e2;
color: #fff;
padding: 20px;
}
.slot-contant {
color: #f00;
font-size: 16px;
}
</style>