vue3中使用@vueuse/core中的圖片懶加載案例詳解
更新時間:2023年03月16日 09:55:00 作者:jjw_zyfx
這篇文章主要介紹了vue3中使用@vueuse/core中的圖片懶加載案例,本文通過實例代碼給大家介紹的非常詳細,需要的朋友可以參考下
1、首先安裝
npm i @vueuse/core
2、新建一個helloworld.js文件,內(nèi)容如下:
import { useIntersectionObserver } from '@vueuse/core' import {ref} from "vue"; export const useLazyData = (apiFn) => { const result = ref([]) const target = ref(null) // stop 停止觀察 const { stop } = useIntersectionObserver( // 監(jiān)聽的目標元素 target, ([{ isIntersecting }], observerElement) => { // isIntersecting 是否進入可視區(qū) if (isIntersecting) { stop() // 調(diào)用API函數(shù)獲取數(shù)據(jù) const aa = apiFn() console.log('aa', aa) result.value = aa // // 調(diào)用API函數(shù)獲取數(shù)據(jù) // apiFn().then(data => { // result.value = data.result // }) } }, // 配置選項,相交的比例大于0就觸發(fā) { 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') // 發(fā)送請求的函數(shù) // 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、觀察效果:會發(fā)現(xiàn)當滾輪滑到底部時右邊控制臺會打印,沒滑動到底部則不會打印,同時顯示出下邊的顏色
到此這篇關(guān)于vue3中使用@vueuse/core中的圖片懶加載案例詳解的文章就介紹到這了,更多相關(guān)vue3圖片懶加載內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
vue3?setup語法糖中獲取slot插槽的dom對象代碼示例
slot元素是一個插槽出口,標示了父元素提供的插槽內(nèi)容將在哪里被渲染,這篇文章主要給大家介紹了關(guān)于vue3?setup語法糖中獲取slot插槽的dom對象的相關(guān)資料,文中通過代碼介紹的非常詳細,需要的朋友可以參考下2024-04-04Vue中data傳遞函數(shù)、props接收函數(shù)及slot傳參的使用及說明
這篇文章主要介紹了Vue中data傳遞函數(shù)、props接收函數(shù)及slot傳參的使用及說明,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-10-10