【vue3】vue3中封装懒加载指令
在图片很多的电商网站,或者是大量图片展示的企业官网中,性能优化的一个关键技术点就是图片的延迟加载,即懒加载
优点就是减少了图片的http请求次数,减轻服务器压力
实现效果
代码实现
这里借助于第三方的vue3专用的工具库VueUse
来封装懒加载指令
import { ref } from "vue";
import { useIntersectionObserver } from "@vueuse/core";
import loading from "@a/images/loading.gif";const vLazyImg = {name: "lazy-img", mounted: (el, bingding) => {const target = ref(el);const targetIsVisible = ref(false);const { stop } = useIntersectionObserver(target,([{ isIntersecting }], observerElement) => {targetIsVisible.value = isIntersecting;if (isIntersecting) {el.src = bingding.value;// 优化性能,停止监听stop();} else {el.src = loading;}});},
};
export default vLazyImg;
-
使用说明
1.name: "lazy-img"
纪实指令的名称,也就是我们在模版中用来关联某个dom节点,一般使用方式是加上前缀v-
2.useIntersectionObserver
开启监听后会一直存在,需要我们在监听完成后要手动销毁这个监听器,减少内存的占用 -
指令注册
可以注册成全局的也可以是局部的,根据使用的范围来定
也可以注册成插件的形式,来全局使用
import vHighlight from "./modules/v-highlight";
import vLazy from "./modules/v-lazy";const directives = [vHighlight, vLazy];function createDirectives(app) {for (const directive of directives) {app.directive(directive.name, directive);}
}export default createDirectives;
// main.js注册自定义插件
app.use(customPlugin);
- 组件使用方法
<li v-for="item in newList" :key="item.id"><router-link :to="`/detail/${item.id}`"><img v-lazy-img="item.picture" alt="" /><p class="name ellipsis">{{ item.name }}</p><p class="price">¥{{ item.price }}</p></router-link>
</li>