vue3监听元素高度

2,882 阅读1分钟
<div ref="number"></div>
<script setup>
import { ref,onMounted,onUnmounted,watch } from "vue";
let number = ref(null);
let isTrue = ref(false);
let top = ref(null);
function handleScrollx() {
  // console.log("距离顶部高度", number.value.getBoundingClientRect().top);
  top.value = number.value.getBoundingClientRect().top;
  if (top.value < 600) {
    isTrue.value = true;
  }
}
onMounted(() => {
  window.addEventListener("scroll", handleScrollx, true);
});
onUnmounted(() => {
  // 离开该页面需要移除这个监听的事件,不然会报错
  window.removeEventListener("scroll", handleScrollx, true);
});
watch(
  () => top.value,
  (pev, old) => {
    window.addEventListener("scroll", handleScrollx, true);
  }
);
</script>