vue.js 3.2.22:用@vueuse/core实现图片懒加载(@vueuse/core@7.0.3)
一,安装所需的库@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