vue3指令实现图片的懒加载

229 阅读1分钟

前言

图片懒加载是首屏性能优化的一部分,原理是视窗看见图片区域后再加载图片,而不是一打开网页就加载图片

方法

  1. 在src下建立directives文件夹装可能复用的自定义组件,然后在js文件中编写如下代码
    export default{
        mounted(el){
            // 获取元素上的src属性,也就是图片地址
           const imgSrc = el.src
           // 将原本元素的src清空,使其不加载图片
            el.src = ''
            // 观察者
            // 创建一个观察者对象,接收一个回调函数,在元素进入可视区域时会触发该元素
            const observer = new IntersectionObserver( ([{isIntersecting}])=>{
                // 元素出现在可视区域和离开可视区域时会触发
                if(isIntersecting){
                    // 将图片地址赋给元素,加载图片
                    el.src = imgSrc
                    // 停止观察
                    observer.unobserve(el)
                }
            })
            // 监视el元素
            observer.observe(el)
        }
    } 
    

2. 在main.js中挂载自定义指令

import { createApp } from 'vue'
import './style.css'
import App from './App.vue'
// 导入自定义指令
import lazy from './directives/lazy'
const app = createApp(App)
// 挂载自定义指令
app.directive('lazy',lazy)

app.mount('#app')
  1. 在组件中使用自定义指令
  <template>
    <div class="background">
      <img 
      src="../assets/images/page1/0000.jpg"
       alt=""
       v-lazy
       ></div>
  </template>
  
  <script setup>
  import { ref } from "vue"
  
  </script>
  
  <style lang="less" scoped>
  .background {
    width: 100vw;
    height: 100vh;
  }
  </style>