前端vue3實現(xiàn)圖片懶加載的完整步驟記錄
場景和指令用法
場景:電商網站的首頁通常會很長,用戶不一定能訪問到頁面靠下面的圖片,這類圖片通過懶加載優(yōu)化手段可以做到只有進入視口區(qū)域才發(fā)送圖片請求
核心原理:圖片進入視口才發(fā)送資源請求

首先:我們需要定義一個全局的指令,vue3官方的實現(xiàn)方法是這樣的
第一步:熟悉指令語法

并且:還需要用到一個鉤子函數(shù)

第二步:判斷圖片是否進入視口
我們可以使用useIntersectionObserver這個函數(shù)
以下是官方示例的使用方法:
<script setup lang="ts">
import { useIntersectionObserver } from '@vueuse/core'
const { stop } = useIntersectionObserver(
target,
([entry], observerElement) => {
targetIsVisible.value = entry?.isIntersecting || false
},
)
</script>target:需要監(jiān)聽的元素
isIntersecting:是一個布爾值 監(jiān)聽是否進入可視區(qū)
以下是完整代碼實現(xiàn)
main.js
import { useIntersectionObserver } from '@vueuse/core'
const app = createApp(App)
// 定義全局指令
app.directive('img-lazy', {
mounted(el, binding) {
// el: 指令綁定的元素
// binding: binding.value 指令的綁定值 圖片url
console.log(el, binding.value);
useIntersectionObserver(
el, // 監(jiān)聽的元素
([{ isIntersecting }]) => {
// isIntersecting是一個布爾值 監(jiān)聽是否進入可視區(qū)
console.log(isIntersecting);
if (isIntersecting) {
// 圖片進入可視區(qū) 設置圖片的src
el.src = binding.value
}
}
)
}
})在需要懶加載的圖片標簽里使用這個即可
<img v-img-lazy="item.picture" alt="" />
頁面效果

由上圖可以看出在剛進入頁面時需要懶加載的圖片沒有加載出來

由上圖可以看出當頁面滑動到人氣推薦時url全部都加載出來了
回顧核心步驟代碼

================================補檔優(yōu)化==================================
問題1:邏輯書寫位置不合理問:懶加載指令的邏輯直接寫到入口文件中,合理嗎?
答:不合理,入口文件通常只做一些初始化的事情,不該包含太多的邏輯代碼,可以通過插件的方法把懶加載指令封裝為插件,main.js入口文件只需要負責注冊插件即可

代碼實現(xiàn):
插件代碼

// 定義懶加載指令
import { useIntersectionObserver } from '@vueuse/core'
export const lazyPlugin = {
install(app) {
app.directive('img-lazy', {
mounted(el, binding) {
// el: 指令綁定的元素
// binding: binding.value 指令的綁定值 圖片url
console.log(el, binding.value);
useIntersectionObserver(
el, // 監(jiān)聽的元素
([{ isIntersecting }]) => {
// isIntersecting是一個布爾值 監(jiān)聽是否進入可視區(qū)
console.log(isIntersecting);
if (isIntersecting) {
// 圖片進入可視區(qū) 設置圖片的src
el.src = binding.value
}
}
)
}
})
}
}
main.js
// 引入懶加載指令并且注冊
import { lazyPlugin } from '@/directives'
app.use(lazyPlugin)問題2:重復監(jiān)聽問題uselntersectionObserver對于元素的監(jiān)聽是一直存在的,除非手動停止監(jiān)聽,存在內存浪費
解決思路:在監(jiān)聽的圖片第一次完成加載之后就停止監(jiān)聽
代碼實現(xiàn):
// 定義懶加載指令
import { useIntersectionObserver } from '@vueuse/core'
export const lazyPlugin = {
install(app) {
app.directive('img-lazy', {
mounted(el, binding) {
// el: 指令綁定的元素
// binding: binding.value 指令的綁定值 圖片url
console.log(el, binding.value);
const {stop} = useIntersectionObserver(
el, // 監(jiān)聽的元素
([{ isIntersecting }]) => {
// isIntersecting是一個布爾值 監(jiān)聽是否進入可視區(qū)
console.log(isIntersecting);
if (isIntersecting) {
// 圖片進入可視區(qū) 設置圖片的src
el.src = binding.value
stop()
}
}
)
}
})
}
}總結
到此這篇關于前端vue3實現(xiàn)圖片懶加載的文章就介紹到這了,更多相關前端vue3圖片懶加載內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
vue+vuex+axio從后臺獲取數(shù)據(jù)存入vuex實現(xiàn)組件之間共享數(shù)據(jù)
這篇文章主要介紹了vue+vuex+axio從后臺獲取數(shù)據(jù)存入vuex,組件之間共享數(shù)據(jù),非常具有實用價值,需要的朋友可以參考下2017-04-04
詳解vue中使用vue-quill-editor富文本小結(圖片上傳)
這篇文章主要介紹了詳解vue中使用vue-quill-editor富文本小結(圖片上傳),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2019-04-04

