$nextTick的使用场景
可能只凭一些概念性的讲解还是无法对nextTick机制有很清晰的了解,还是上个示例来了解一下吧。
<template>
<div class="app">
<div ref="contentDiv">{{content}}</div>
<div>在nextTick执行前获取内容:{{content1}}</div>
<div>在nextTick执行之后获取内容:{{content2}}</div>
<div>在nextTick执行前获取内容:{{content3}}</div>
</div>
</template>
<script>
export default {
name:'App',
data: {
content: 'Before NextTick',
content1: '',
content2: '',
content3: ''
},
methods: {
changeContent () {
this.content = 'After NextTick' // 在此处更新content的数据
this.content1 = this.$refs.contentDiv.innerHTML //获取DOM中的数据
this.$nextTick(() => {
// 在nextTick的回调中获取DOM中的数据
this.content2 = this.$refs.contentDiv.innerHTML
})
this.content3 = this.$refs.contentDiv.innerHTML
}
},
mount () {
this.changeContent()
}
}
</script>
当我们打开页面后我们可以发现结果为:
After NextTick 在nextTick执行前获取内容:Before NextTick 在nextTick执行之后获取内容:After NextTick 在nextTick执行前获取内容:Before NextTick
所以我们可以知道,虽然content1和content3获得内容的语句是写在content数据改变语句之后的,但他们属于同一个事件循环中,所以content1和content3获取的还是 'Before NextTick' ,而content2获得内容的语句写在nextTick的回调中,在DOM更新之后再执行,所以获取的是更新后的 'After NextTick'。

浙公网安备 33010602011771号