vue3自定义指令(图片懒加载)

一、作用:

创建类似与v-for、v-on的指令;本文以图片的懒加载为例

注册函数:

app.directive(key, directive);

二、vue3自定义指令钩子函数

created:在绑定元素的 attribute 或事件监听器被应用之前调用。在指令需要附加在普通的 v-on 事件监听器调用前的事件监听器中时,这很有用。

beforeMount:当指令第一次绑定到元素并且在挂载父组件之前调用。

mounted:在绑定元素的父组件被挂载后调用,大部分自定义指令都写在这里。

beforeUpdate:在更新包含组件的 VNode 之前调用。

updated:在包含组件的 VNode 及其子组件的 VNode 更新后调用。

beforeUnmount:在卸载绑定元素的父组件之前调用

unmounted:当指令与元素解除绑定且父组件已卸载时,只调用一次


引用自如下:
原文链接:https://blog.csdn.net/snowball_li/article/details/123549051

三、创建一个懒加载的ts文件如(lazy.ts):

import loading from '@/assets/images/loading.png';
import placeholder from '@/assets/images/placeholder.png';

export default {
beforeMount(el: HTMLImageElement) {
const img = el;
const src = img.getAttribute('src');
if (!src) {
img.setAttribute('src', placeholder);
return;
}
// 图片使用loading gif替换
img.setAttribute('src', loading);
// 新建Image对象
const tempImg = new Image();
tempImg.onload = function () {
img.setAttribute('src',src);
};
tempImg.onerror = () => {
img.setAttribute('src', placeholder);
};
const observer = new IntersectionObserver(function (changes) {
// img元素进入可视区域
changes.forEach((item) => {
if (item.intersectionRatio !== 0) {
tempImg.src = <string>src;
}
});
});
observer.observe(el);
},
};
四、程序入口文件加载该指令:

import type { App, Directive } from 'vue';
import lazy from './lazy';

const app = createApp(App);
app.directive("lazy ", lazy );
五、页面可使用该指令

<img v-lazy :src="pigUrl" />
这样,在img展示图片时,会先展示加载中动画,然后如果能请求到图片就展示图片,否在展示默认图片

六、其他说明

IntersectionObserver可参考js原始用途:IntersectionObserver(交叉观察器)-CSDN博客
————————————————

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。

原文链接:https://blog.csdn.net/q893668680/article/details/136759166

posted @ 2024-06-12 10:38  喜葵  阅读(10)  评论(0编辑  收藏  举报