装置 vueuse
npm i @vueuse/core -S
官网文档
useIntersectionObserver | VueUse
template
<section
class="p-2 font-medium"
ref="target">
要懒加载的 DOM 元素
</section>
script
<script setup>
import {ref} from "vue"
import {useIntersectionObserver} from "@vueuse/core"
const target = ref(null)
const targetIsVisiable = ref(false)
const {stop} = useIntersectionObserver(
target,
([{isIntersecting}], observerElement) => {
// 如果进入可视区域
if (isIntersecting) {console.log("target is visible");
console.log(observerElement);
stop() // 只需懒加载一次
// axios()
// fn()}
targetIsVisiable.value = isIntersecting
console.log(targetIsVisiable.value);
}
)
</script>