vue图片懒加载指令实现
- 在main.js中定义全局指令
-
//引入vueuse三方库 import { useIntersectionObserver } from "@vueuse/core" //定义全局指令 app.directive("img-lazy", {mounted(el, binding) {//el:指令绑定的那个元素//binding:binding.value 指令等于号后面绑定的表达式的值 图片url//console.log(el, binding.value)//拿到stop方法,保证图片只加载一次const {stop}= useIntersectionObserver(el, ([{ isIntersecting }]) => {//测试下它是否到了视口区域console.log(isIntersecting)if (isIntersecting) {//true就进入到视口区域了el.src = binding.valuestop()}})} })
-
对应位置使用
-
<img v-img-lazy="item.picture" alt="" />
-
-
视频源: Day3-05.Home-图片懒加载指令实现_哔哩哔哩_bilibili
代码还可以从main.js抽出封装,详细请见下个视频3-06.