天天看點

自定義指令實作圖檔懶加載

Vue自定義指令實作圖檔懶加載

其實實作懶加載的方式有很多了,現在也有很多插件(比如:vue-lazyload等),element-ui庫中也有圖檔懶加載的方式,是以大家根據自己的喜歡選擇就可以了 

IntersectionObserver 

首先要用到這麼個API,直接可以用的哈,它可以很友善的幫我們監視某個dom元素是否出現在可視區域内 

使用起來也很友善 

// 觀察者
const observer = new IntersectionObserver(([{ isIntersecting }]) => {
  // 如果元素出現在可視區域内,和離開可視區域的時候被觸發
  if(isIntersecting) {
    
  }
})
// 開啟觀察(傳入要觀察的dom元素)
observer.observe(el)      
自定義指令實作圖檔懶加載

這是其中的一些方法 

下面介紹Vue中自定義指令實作懶加載: 

可以在src下建立directive/index.js 

import Vue from 'vue'

// 圖檔懶加載
Vue.directive('lazy', {
  inserted(el) {
    const imgSrc = el.src
    el.src = ''

    // 觀察者
    const observer = new IntersectionObserver(([{ isIntersecting }]) => {
      // 如果元素出現在可視區域内,和離開可視區域的時候被觸發
      if(isIntersecting) {
        // 出現在可視區域,再加載圖檔
        el.src = imgSrc
        // 停止觀察
        observer.unobserve(el)
      }
    })
    // 開啟觀察(傳入要觀察的dom元素)
    observer.observe(el)
  }
})      
import './directive'      
<template>
  <div class="home">
    <!-- 模拟滾動 -->
    <div style="height: 1000px;"></div>
    <!-- 三張圖檔懶加載 -->
    <div v-for="item in 3" :key="item">
      <img v-lazy :src="require(`../assets/${ item }.png`)" alt="">
    </div>
  </div>
</template>      

繼續閱讀