使用vue第三方库 useIntersectionObserver 创建文件 directives/index.js 导入第三方库
import { useIntersectionObserver } from '@vueuse/core'
export const lazyPlugin = {
install(app) {
app.directive('img-lazy', {
mounted(el, binding) {
// el:指令绑定的那个元素 img
// binding: binding.value 指令等于后面绑定的表达式的值
// console.log(el, binding.value)
// stop防止重复渲染
const { stop } = useIntersectionObserver(
el,
([{ isIntersecting }]) => {
// console.log(isIntersecting)
if (isIntersecting) {
el.src = binding.value
stop()
}
}
)
}
})
}
}
main.js引入 挂载
import { lazyPlugin } from './directives'
import App from './App.vue'
const app = createApp(App)
app.use(lazyPlugin)
使用 在需要懒加载的图片标签上添加v-img-lazy属性(注意不需要绑定src了)
index.vue
<img v-img-lazy="item.picture" alt="" />
标签:el,const,useIntersectionObserver,app,binding,lazyPlugin,vue3,加载,图片
From: https://www.cnblogs.com/happy-p/p/17548910.html