图片懒加载
小于 1 分钟约 152 字
自定义指令
/**
* v-lazy
* 图片懒加载
*/
const copy: Directive = {
mounted(el: HTMLImageElement) {
const imgSrc = el.src
el.src = ''
const observer = new IntersectionObserver(([{ isIntersecting }]) => {
// 元素出现在可视区域和离开可视区域触发
if (isIntersecting) {
// 加载图片
el.src = imgSrc
// 停止观察
observer.unobserve(el)
}
})
observer.observe(el)
},
}
export default copy
注册指令
import type { App } from "vue"
import lazy from "./modules/lazy"
const directivesList: any = {
lazy
}
const directives = {
install: function (app: App<Element>) {
Object.keys(directivesList).forEach(key => {
// 注册自定义指令
app.directive(key, directivesList[key])
})
}
}
export default directives
main.ts
import directives from "./directives/index"
app.use(directives)
使用
<img :src="img" v-lazy />