前情提要:當(dāng)頁面有很多圖片要展示的時(shí)候崖咨,為了不造成資源浪費(fèi),暫未在窗口可視區(qū)域的圖片著洼,可以采用圖片懶加載的功能易茬。
1. 安裝VueUse npm i @vueuse/core
VueUse 是一個(gè)基于 Composition API 的實(shí)用程序函數(shù)集合。
VueUse 官網(wǎng)地址:https://vueuse.org
useIntersectionObserver函數(shù) 如下圖介紹
屏幕截圖 2023-09-25 194359.png
2. 在main.js中全局注冊該自定義指令
import { useIntersectionObserver } from '@vueuse/core'
// 定義全局命令
app.directive('img-lazy', {
mounted(el, binding) {
// el:指定綁定的那個(gè)元素 img
// binding: binding.value 指令等于后面綁定的表達(dá)式的值 圖片的地址
console.log(el, binding)
useIntersectionObserver(
el,
([{ isIntersecting }]) => {
if (isIntersecting) {
el.src = binding.value
}
},
)
}
})
3. 在頁面使用該指令
<img v-img-lazy="item.picture" alt="">
刷新頁面萧吠,發(fā)現(xiàn)圖片懶加載功能已經(jīng)實(shí)現(xiàn)左冬。
代碼優(yōu)化
思考:懶加載指令放在main.js入口文件里面合理嗎?
答:不合理纸型,入口文件通常只做一些初始化的事情拇砰,不應(yīng)該包含太多的邏輯的代碼,可以通過插件的方法狰腌,把懶加載指令封裝為插件除破。
- 在src下面新建directives/index.js 文件
import { useIntersectionObserver } from '@vueuse/core'
export const lazyPlugin = {
install(app) {
// 定義懶加載指令
app.directive('img-lazy', {
mounted(el, binding) {
console.log(el, binding)
useIntersectionObserver(
el,
([{ isIntersecting }]) => {
if (isIntersecting) {
el.src = binding.value
}
},
)
}
})
}
}
- 在main.js入口文件中注冊該組件
import { lazyPlugin } from '@/directives'
app.use(lazyPlugin)
問題:useIntersectionObserver 對于函數(shù)的監(jiān)聽是一直都存在的,除非手動停止監(jiān)聽琼腔,否則會造成資源浪費(fèi)問題瑰枫。
解決思路:在圖片的第一次加載完成之后就停止監(jiān)聽
const { stop } = useIntersectionObserver(
el,
([{ isIntersecting }]) => {
if (isIntersecting) {
el.src = binding.value
stop()
}
},
)
以上就是今天寫的內(nèi)容啦,希望和大家一起共同學(xué)習(xí)丹莲,如果有錯(cuò)誤希望給我回復(fù)喔O(∩_∩)O~