使用自定义指令实现图片懒加载和默认图片

@/directives/index.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
// 定义懒加载插件
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()
}
})
},
})
app.directive('imagerror', {
mounted(el, binding) {
el.src = el.src || binding.value
el.onerror = function () {
// 当图片出现异常的时候 会将指令配置的默认图片设置为该图片的内容
// dom可以注册error事件
el.src = binding.value // 这里不能写死
},
updated() {
el.src = el.src || binding.value
}
},
})
},
}

main.js

1
2
3
4
5
6
import App from './App.vue'
// 引入懒加载指令插件并且注册
import { lazyPlugin } from '@/directives'
const app = createApp(App)
app.use(lazyPlugin)
app.mount('#app')
  • 版权声明: 本博客所有文章除特别声明外,著作权归作者所有。转载请注明出处!
  • Copyrights © 2023-2025 congtianfeng
  • 访问人数: | 浏览次数: