玖叶教程网

前端编程开发入门

vue3图片懒加载指令实现(vue引入图片报错)




1.定义全局指令 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 指令等于号后面绑定的表达式的值 图片url

// console.log(el, binding.value)

const { stop } = useIntersectionObserver(

el,

([{ isIntersecting }]) => {

console.log(isIntersecting)

if (isIntersecting) {

// 进入视口区域

el.src = binding.value

stop()

}

},

)

}

})

}

}

2.引用该指令

-- main.js

// 引入懒加载指令插件并且注册

import { lazyPlugin } from '@/directives'

app.use(lazyPlugin)

-- template 中

<img v-img-lazy="item.picture" alt="">

发表评论:

控制面板
您好,欢迎到访网站!
  查看权限
网站分类
最新留言