vue3中使用@vueuse/core中的图片懒加载案例详解
更新时间:2023年03月16日 09:55:00 作者:jjw_zyfx
这篇文章主要介绍了vue3中使用@vueuse/core中的图片懒加载案例,本文通过实例代码给大家介绍的非常详细,需要的朋友可以参考下
1、首先安装
npm i @vueuse/core
2、新建一个helloworld.js文件,内容如下:
import { useIntersectionObserver } from '@vueuse/core' import {ref} from "vue"; export const useLazyData = (apiFn) => { const result = ref([]) const target = ref(null) // stop 停止观察 const { stop } = useIntersectionObserver( // 监听的目标元素 target, ([{ isIntersecting }], observerElement) => { // isIntersecting 是否进入可视区 if (isIntersecting) { stop() // 调用API函数获取数据 const aa = apiFn() console.log('aa', aa) result.value = aa // // 调用API函数获取数据 // apiFn().then(data => { // result.value = data.result // }) } }, // 配置选项,相交的比例大于0就触发 { threshold: 0 } ) return { result, target } }
3、再app.vue中导包并使用
<template> <div> <div class="up"></div> <div ref="target" :style="{backgroundColor: bgc}" class="down"></div> </div> </template> <script setup> import {useLazyData} from "@/helloworld"; import {nextTick, onMounted, ref} from "vue"; let bgc = ref('#000') // 发送请求的函数 // export const findNew = () => { // return request('/home/new', 'get') // } const qingqiuhanshu = () => { // 模仿请求 return '#1DC779' } const { target, result } = useLazyData(qingqiuhanshu) bgc = result </script> <style lang="less" scoped> .up{ height: 100vh; margin-bottom: 20px; background-color: pink; } .down{ height: 50px; background-color: deeppink; } </style>
4、观察效果:会发现当滚轮滑到底部时右边控制台会打印,没滑动到底部则不会打印,同时显示出下边的颜色
到此这篇关于vue3中使用@vueuse/core中的图片懒加载案例详解的文章就介绍到这了,更多相关vue3图片懒加载内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
相关文章
修改el-form-item中的label里面的字体边距或者大小问题
这篇文章主要介绍了修改el-form-item中的label里面的字体边距或者大小问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教2023-10-10
最新评论