阅读以下代码,请选择可以正确打印h1标签宽度的选项( )
<template>
<div>
<h1 ref='h1' v-if="show">nowcoder</h1>
</div>
</template>
<script>
export default {
data() {
return {
show: false
}
},
mounted() {
this.show = true
// 此处填写代码
}
}
</script>
A
this.$nextTick(function() {
console.log(this.$refs.h1.offsetWidth)
})
B
setInterval(() => {
console.log(this.$refs.h1.offsetWidth)
})
C
setTimeout(() => {
console.log(this.$refs.h1.offsetWidth)
})
D
console.log(this.$refs.h1.offsetWidth)
正确答案:ABC
Vue实现响应式并不是数据发生变化之后DOM立即变化,而是在同步任务执行完成之后才执行渲染任务,简单说Vue的渲染是异步的。
使用 nextTick和异步任务函数能够确保视图更新完之后再获取到h1的 offsetWidth,nextTick大家基本都懂,js是单线程语言,异步任务在任务队列中等待同步任务执行结束后再执行,B和C选项同样保证了在视图更新完之后再获取。