一,安裝所需的庫@vueuse/core
liuhongdi@lhdpc:/data/vue/lazy$ npm install --save @vueuse/core
說明:劉宏締的架構森林是一個專注架構的博客,
網站:https://blog.imgtouch.com
本文: https://blog.imgtouch.com/index.php/2023/05/28/vue-js-3-2-22-yong-vueuse-core-shi-xian-tu-pian-lan-jia-zai/
對應的源碼可以訪問這里獲取: https://github.com/liuhongdi/
或: https://gitee.com/liuhongdi
說明:作者:劉宏締 郵箱: 371125307@qq.com
二,編寫代碼
1,directive/LazyImage.js
import { useIntersectionObserver } from '@vueuse/core'
export default {
install (app) {
app.directive('lazySrc', {
mounted (el, binding) {
let imgDefault="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7";
el.src = imgDefault // 指定默認顯示內容
const { stop } = useIntersectionObserver(el, ([{ isIntersecting }]) => {
if (isIntersecting) { // 如果在可見區域中
el.onerror = () => { //如圖片加載失敗
el.src = imgDefault
}
stop() //如已在可見區域內則下次不再監聽
//set url
el.src = binding.value
console.log(el.src+'加載成功');
//set style
el.className = 'imgFade';
}
}, { threshold: 0 }) // 當可視區域寬高為0就觸發
//console.log(el, binding.value)
}
})
}
}
2,main.js
import { createApp } from 'vue'
import App from './App.vue'
import LazyImage from '@/directive/LazyImage'
createApp(App).use(LazyImage).mount('#app')
3,Lazy.vue
<template> <div style="width:100%;height:100vh;display: flex;flex-direction: column;"> <img style="width:100%;" v-lazySrc="'https://imgs-qn.iliangcang.com//ware/ueditor/image/20211105/1636086111740260.jpg'" /> <img style="width:100%;" v-lazySrc="'https://imgs-qn.iliangcang.com/ware/slider/1757.jpg'" /> <img style="width:100%;" v-lazySrc="'https://imgs-qn.iliangcang.com/ware/sowhatimg/ware/orig/2/37/37757.jpg'" /> <img style="width:100%;" v-lazySrc="'https://imgs-qn.iliangcang.com/ware/sowhatimg/ware/orig/2/34/34656.png'" /> <img style="width:100%;" v-lazySrc="'https://imgs-qn.iliangcang.com/ware/slider/1759.jpg'" /> <img style="width:100%;" v-lazySrc="'https://imgs-qn.iliangcang.com/ware/sowhatimg/ware/orig/2/37/37753.jpg'" /> <img style="width:100%;" v-lazySrc="'https://imgs-qn.iliangcang.com//ware/ueditor/image/20211112/1636699398743493.jpg'" /> <img style="width:100%;" v-lazySrc="'https://imgs-qn.iliangcang.com/ware/slider/1753.jpg'" /> </div> </template> <script> export default { name: "Lazy", setup() { } } </script> <style scoped> .imgFade { animation: fadeIn 1.5s linear; } @keyframes fadeIn { from { opacity: 0; } to { opacity: 1; } } </style>
三,測試效果

四,查看vue的版本:
liuhongdi@lhdpc:/data/vue/lazy$ npm list vue lazy@0.1.0 /data/vue/lazy ├─┬ @vue/cli-plugin-babel@4.5.15 │ └─┬ @vue/babel-preset-app@4.5.15 │ └── vue@3.2.22 deduped ├─┬ @vueuse/core@7.0.3 │ ├─┬ @vueuse/shared@7.0.3 │ │ └── vue@3.2.22 deduped │ ├─┬ vue-demi@0.12.1 │ │ └── vue@3.2.22 deduped │ └── vue@3.2.22 deduped └─┬ vue@3.2.22 └─┬ @vue/server-renderer@3.2.22 └── vue@3.2.22 deduped
