vue3 图片懒加载

使用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="" />
 
posted @ 2023-07-12 21:24  Happy-P  阅读(300)  评论(0)    收藏  举报