- vue中的dom更新是异步的,参考下面的例子:
<template>
<div>
<div
style="width: 20vw; height: 10vw; border: 1px solid #000000"
@click="updateData"
ref="box"
>
{{ msg }}
</div>
</div>
</template>
<script>
export default {
data() {
return {
msg: "我是msg",
};
},
methods: {
updateData() {
this.msg = "msg改变了";
console.log(this.$refs.box.innerHTML);
},
},
};
</script>
输出 我是msg
- 如果想要视图更新之后立刻获取更新后的dom元素,可以使用$nextTick
<template>
<div>
<div
style="width: 20vw; height: 10vw; border: 1px solid #000000"
@click="updateData"
ref="box"
>
{{ msg }}
</div>
</div>
</template>
<script>
export default {
data() {
return {
msg: "我是msg",
};
},
methods: {
updateData() {
this.msg = "msg改变了";
this.$nextTick(() => {
console.log(this.$refs.box.innerHTML);
})
},
},
};
</script>
输出 msg改变了