src-directive-lazy-index.js
import { useIntersectionObserver } from '@vueuse/core'
const lazy = (app) => {
app.directive('lazy', {
mounted(el, binding) {
const { stop } = useIntersectionObserver(
el,
([{ isIntersecting }]) => {
if (isIntersecting) {
el.src = binding.value
stop()
}
}
)
}
})
}
export default lazy
main.js
import lazy from "@/directive/lazy";
app.use(lazy)
<img v-lazy="图片路径" />
还有一个问题 记得写图片大小否则懒加载会失效