代码如下
<template>
<div>
<div ref="divR" class="aC" @click="changeF"></div>
<p v-if="clientHeight">{{clientHeight}}</p>
</div>
</template>
<script>
import { ref,watchEffect,onMounted } from 'vue';
export default {
props: {
},
data() {
return {
}
},
setup(props,context) {
const divR = ref(null);
const clientHeight = ref(0);
watchEffect(() => {
// 侦听模板引用
clientHeight.value = divR.value.clientHeight;
},{
// 使用flush: 'post' 确保模板引用与 DOM 保持同步,并引用正确的元素
flush: 'post'
})
return {
clientHeight,
divR, // 在setup中暴露 divR,并通过 ref="divR",将其绑定到 div 作为其 ref
}
},
methods: {
changeF() {
this.clientHeight = (this.divR.clientHeight * Math.random()).toFixed(0);
}
}
}
</script>
<style scoped>
.aC {
width: 100px;
height: 100px;
background: red;
}
</style>
效果如下