溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶(hù)服務(wù)條款》

vue3圖片懶加載IntersectionObserver和useIntersectionObserver怎么用

發(fā)布時(shí)間:2023-03-16 10:30:03 來(lái)源:億速云 閱讀:104 作者:iii 欄目:開(kāi)發(fā)技術(shù)

這篇文章主要介紹“vue3圖片懶加載IntersectionObserver和useIntersectionObserver怎么用”的相關(guān)知識(shí),小編通過(guò)實(shí)際案例向大家展示操作過(guò)程,操作方法簡(jiǎn)單快捷,實(shí)用性強(qiáng),希望這篇“vue3圖片懶加載IntersectionObserver和useIntersectionObserver怎么用”文章能幫助大家解決問(wèn)題。

1、在src下創(chuàng)建helloworld.js 內(nèi)容如下

// 隨便導(dǎo)入一張圖片作為加載出錯(cuò)時(shí)的默認(rèn)圖片
import defaultImg from '@/assets/logo.svg'

import {useIntersectionObserver} from "@vueuse/core"; //圖片加載失敗時(shí)候用的圖片
export default {
    install (app) {
        defineDirective(app)//自定義指令
    }
}

// 自定義指令
const defineDirective = (app) => {
    // 1.圖片懶加載指令v-lazyLoad
// 原理:先存儲(chǔ)圖片地址不能在src上,當(dāng)圖片進(jìn)入可視區(qū),將你存儲(chǔ)圖片地址設(shè)置給圖片元素(dom)的src即可。
    app.directive('lazyLoad', {
        // vue2.0監(jiān)聽(tīng)使用指令的DOM是否創(chuàng)建好,鉤子函數(shù): inserted
        // vue3.0 的指令擁有的鉤子函數(shù)和組件的一樣,使用指令的DON是否創(chuàng)建好,鉤子函數(shù): mounted,onMounted是在組合API時(shí)候使用,現(xiàn)在是選項(xiàng)
        mounted (el, binding) { // 綁定的元素,綁定的值
            // // 2.創(chuàng)建一個(gè)觀(guān)察對(duì)象,來(lái)觀(guān)察當(dāng)前使用指令得元素

            const observe = new IntersectionObserver(([{isIntersecting}]) => {
                if (isIntersecting) { // 如果進(jìn)入了可視區(qū)
                    // 誰(shuí)進(jìn)入了可視區(qū)?得用observe去觀(guān)察 是哪個(gè)元素使用了該指令,所以會(huì)傳入dom對(duì)象el
                    // 停止觀(guān)察,因?yàn)橛^(guān)察一次就夠了
                    observe.unobserve(el)
                    // console.log(binding.value, el) // binding.value就是綁定的地址
                    // 3.監(jiān)聽(tīng)圖片加載失敗,用默認(rèn)圖
                    el.onerror = () => {
                        el.src = defaultImg
                    }
                    // 4.將指令v-lazyLoad上的地址設(shè)置給el的src屬性
                    el.src = binding.value
                }
            }, {
                threshold: 0//進(jìn)入到可視區(qū)交界就開(kāi)始觀(guān)察
            })
            observe.observe(el)// 使用observe上的observe方法觀(guān)察這個(gè)dom元素
        }
            // const { stop } = useIntersectionObserver(
            //     // 監(jiān)聽(tīng)目標(biāo)元素
            //     el,
            //     ([{ isIntersecting }], observerElement) => {
            //         if (isIntersecting) {
            //             // 當(dāng)圖片url無(wú)效加載失敗的時(shí)候使用默認(rèn)圖片替代
            //             el.onerror = function () {
            //                 el.src = defaultImg
            //             }
            //             console.log('加載')
            //             el.src = binding.value
            //             stop()
            //         }
            //     })
            // }
    })
}

上邊的代碼中mounted下邊這個(gè)是一種方式,這種方式不借助插件即不用安裝任何東西

const observe = new IntersectionObserver(([{isIntersecting}]) => {
        if (isIntersecting) { // 如果進(jìn)入了可視區(qū)
            // 誰(shuí)進(jìn)入了可視區(qū)?得用observe去觀(guān)察 是哪個(gè)元素使用了該指令,所以會(huì)傳入dom對(duì)象el
            // 停止觀(guān)察,因?yàn)橛^(guān)察一次就夠了
            observe.unobserve(el)
            // console.log(binding.value, el) // binding.value就是綁定的地址
            // 3.監(jiān)聽(tīng)圖片加載失敗,用默認(rèn)圖
            el.onerror = () => {
                el.src = defaultImg
            }
            // 4.將指令v-lazyLoad上的地址設(shè)置給el的src屬性
            el.src = binding.value
        }
    }, {
        threshold: 0//進(jìn)入到可視區(qū)交界就開(kāi)始觀(guān)察
    })
    observe.observe(el)// 使用observe上的observe方法觀(guān)察這個(gè)dom元素
}

mounted 下邊帶注釋的是另一種方式,這種方式需要安裝插件安裝過(guò)程點(diǎn)擊進(jìn)入教程

// const { stop } = useIntersectionObserver(
//     // 監(jiān)聽(tīng)目標(biāo)元素
//     el,
//     ([{ isIntersecting }], observerElement) => {
//         if (isIntersecting) {
//             // 當(dāng)圖片url無(wú)效加載失敗的時(shí)候使用默認(rèn)圖片替代
//             el.onerror = function () {
//                 el.src = defaultImg
//             }
//             console.log('加載')
//             el.src = binding.value
//             stop()
//         }
//     })
// }

2、在main.js中導(dǎo)入并使用

import { createApp } from 'vue'
import App from './App.vue'
import './assets/reset.css'
import Vant from 'vant'
import 'vant/lib/index.css';
// 導(dǎo)入自己UI組件庫(kù)
import UI from './helloworld'

// 插件的使用,在main.js使用app.use(插件)
createApp(App).use(Vant).use(UI).mount('#app')
// 具體就是導(dǎo)入這個(gè)
// import UI from './helloworld'
// 再u(mài)se(UI)

3、再app.vue中使用如下:

<template>
  <div class="cs"></div>
  <ul >
    <li v-for="item in image_list" :key="item">
<!--      原本的寫(xiě)法-->
      <!-- <img :src="item.picture"  alt=""> -->
<!--      // 使用圖片懶加載指令-->
      <img v-lazyLoad="item"  alt="">
    </li>
  </ul>
</template>
<script setup>
import {nextTick, onMounted, ref} from "vue";
const image_list = ref([
    'https://yanxuan-item.nosdn.127.net/a6939f41c48fa9e9c8f7a7ed855351f1.jpg',
    'https://yanxuan-item.nosdn.127.net/0cdfd546f8675669b87716114ad5900a.jpg',
    'https://yanxuan-item.nosdn.127.net/240983ccc935146a4795e3990d30468d.jpg',
    'https://yanxuan-item.nosdn.127.net/d46e005025a5d3b73c4781d31b327558.jpg',
    'https://yanxuan-item.nosdn.127.net/330913911087b44b0d817dd78233165f.png',
    'https://yanxuan-item.nosdn.127.net/9d9590bdb4f7cdd874de6a4554abcff9.jpg',
    'https://yanxuan-item.nosdn.127.net/cd9060820a1a52f296fa2502e56a5872.jpg'
])
</script>

<style lang="less" scoped>
.cs{
  height: 1000px;
  background-color: pink;
}
.outer{
  img{
    display: inline-block;
    width: 500px;
  }
}
.inner{
  display: inline-block;
  width: 500px;
  height: 50px;
  background-color: deeppink;
}
</style>

關(guān)于“vue3圖片懶加載IntersectionObserver和useIntersectionObserver怎么用”的內(nèi)容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業(yè)相關(guān)的知識(shí),可以關(guān)注億速云行業(yè)資訊頻道,小編每天都會(huì)為大家更新不同的知識(shí)點(diǎn)。

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀(guān)點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI