vue3中使用@vueuse/core中的圖片懶加載案例詳解
1、首先安裝
npm i @vueuse/core
2、新建一個(gè)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)聽的目標(biāo)元素 target, ([{ isIntersecting }], observerElement) => { // isIntersecting 是否進(jìn)入可視區(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 // }) } }, // 配置選項(xiàng),相交的比例大于0就觸發(fā) { threshold: 0 } ) return { result, target } }
3、再app.vue中導(dǎo)包并使用
<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ā)送請(qǐng)求的函數(shù) // export const findNew = () => { // return request('/home/new', 'get') // } const qingqiuhanshu = () => { // 模仿請(qǐng)求 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、觀察效果:會(huì)發(fā)現(xiàn)當(dāng)滾輪滑到底部時(shí)右邊控制臺(tái)會(huì)打印,沒滑動(dòng)到底部則不會(huì)打印,同時(shí)顯示出下邊的顏色
到此這篇關(guān)于vue3中使用@vueuse/core中的圖片懶加載案例詳解的文章就介紹到這了,更多相關(guān)vue3圖片懶加載內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- 解決安裝vue3腳手架@vue/cli報(bào)4048錯(cuò)誤問題
- vue3+js+elementPlus使用富文本編輯器@vueup/vue-quill詳細(xì)教程
- 解決@vue/cli安裝成功后,運(yùn)行vue -V報(bào):不是內(nèi)部或外部命令的問題
- npm install -g @vue/cli安裝vue腳手架報(bào)錯(cuò)問題(一般都能解決)
- 解決vue運(yùn)行報(bào)錯(cuò)Error:Cannot?find?module?'@vue/cli-plugin-babel'
- VUE2舊項(xiàng)目重新安裝依賴后@vue/compiler-sfc編譯報(bào)錯(cuò)問題
相關(guān)文章
一文搞明白vue開發(fā)者vite多環(huán)境配置
Vue是一款流行的JavaScript框架,用于開發(fā)動(dòng)態(tài)單頁應(yīng)用程序,本地安裝和環(huán)境配置是學(xué)習(xí)和使用Vue的第一步,下面這篇文章主要給大家介紹了關(guān)于vue開發(fā)者vite多環(huán)境配置的相關(guān)資料,需要的朋友可以參考下2023-06-06vue實(shí)現(xiàn)左右點(diǎn)擊滾動(dòng)效果
這篇文章主要為大家詳細(xì)介紹了vue實(shí)現(xiàn)左右點(diǎn)擊滾動(dòng)效果,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-01-01Vue3 + MybatisPlus實(shí)現(xiàn)批量刪除功能(詳細(xì)代碼)
這篇文章主要介紹了Vue3 + MybatisPlus實(shí)現(xiàn)批量刪除功能,本文通過實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友參考下吧2024-03-03vue引入elementUi后打開頁面報(bào)錯(cuò)Uncaught?TypeError的解決方式
這篇文章主要給大家介紹了關(guān)于vue引入elementUi后打開頁面報(bào)錯(cuò)Uncaught?TypeError:?Cannot?read?properties?of?undefined(reading?‘prototype‘)的解決方式,文中通過圖文介紹的非常詳細(xì),需要的朋友可以參考下2022-08-08vue3.0中使用websocket,封裝到公共方法的實(shí)現(xiàn)
這篇文章主要介紹了vue3.0中使用websocket,封裝到公共方法的實(shí)現(xiàn),具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-10-10