图片懒加载
vue
<img
ref="imgRef"
:data-src="icon"
:src="def"
alt=""
/>
1
2
3
4
5
6
2
3
4
5
6
ts
import { ref, watchEffect } from 'vue'
const icon = 'http://localhost:5173/vite-press/logo.svg'
const def = '/default.img'
const imgRef = ref<HTMLImageElement | null>(null)
const observer = new IntersectionObserver(entries => {
entries.forEach(entry => {
if (entry.isIntersecting) {
const lazyImg = entry.target as HTMLImageElement
const src = lazyImg.dataset.src
if (src) {
lazyImg.src = src
lazyImg.removeAttribute('data-src')
}
observer.unobserve(lazyImg)
}
})
})
watchEffect(() => {
if (imgRef.value) {
observer.observe(imgRef.value)
}
})
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24