虽然 Vue 是数据驱动的,但是有时候我们不得不去操作 DOM 去处理一些特殊的场景,而 Vue 更新 DOM 是异步执行的,所以我们不得不去使用 $nextTick 去异步获取 DOM。
<template>
<div>
<span ref="msg">{{ msg }}</span>
</div>
</template>
<script>
export default {
data() {
return {
msg: 'hello nextTick'
}
},
methods: {
changeMsg() {
this.msg = 'hello world'
console.log(this.$refs.msg.innerHTML, '同步获取')
this.$nextTick(() => {
console.log(this.$refs.msg.innerHTML, '异步获取')
})
}
},
mounted() {
this.changeMsg()
}
}
</script>