自定义指令图片懒加载
导入默认图片;
import defaultImg from "@/assets/images/200.png";
export default {
install(Vue) {
// // 注册自定义指令 v2方法
Vue.directive("lazy", {
// inserted () {
// console.log(11111)
// }
//注册自定义指令 v3方法
mounted(el, binding) {
// 浏览器提供 IntersectionObserver
const observer = new IntersectionObserver(
([{ isIntersecting }]) => {
// console.log(isIntersecting, '====IntersectionObserver')
if (isIntersecting) {
console.log(el, binding, 11111);
// 图片加载失败就显示默认图片
el.onerror = function () {
el.src = defaultImg;
};
el.src = binding.value;
// 不在监听dom
observer.unobserve(el);
}
},
{
threshold: 0.01,
}
);
// 监听dom
observer.observe(el);
},
});
},
};
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
37
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
37
上次更新: 2024/08/07, 18:05:11