基本代码
<template>
<div>
<div style="height:2000px"></div>
<img ref="target" src="" alt="">
</div>
</template>
<script lang='ts' setup>
import { ref,reactive } from 'vue'
import {useIntersectionObserver} from '@vueuse/core'
const target = ref<HTMLImageElement|null>(null)
useIntersectionObserver(target, ([{isIntersecting}]) =>{
const src = 'https://ts3.cn.mm.bing.net/th?id=OIP-C.Zxtf2X2EddV-g7hKyBhilAHaQB&w=161&h=350&c=8&rs=1&qlt=90&o=6&pid=3.1&rm=2'
if(isIntersecting){
if(target.value){
target.value.src = src
}
}
})
</script>
<style scoped>
</style>
封装为自定义指令
export default function (app: App<Element>) {
app.directive('lazy', {
mounted(el, binding) {
const { stop } = useIntersectionObserver(el,([{ isIntersecting }]) => {
if(isIntersecting){
el.src = binding.value
el.onerror = function() {
el.src = defaultImg
}
}
stop()
})
},
})
}