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( // 監(jiān)聽的目標元素 target, ([{ isIntersecting }], observerElement) => { // isIntersecting 是否進入可視區(qū) if (isIntersecting) { stop() // 調用API函數獲取數據 const aa = apiFn() console.log('aa', aa) result.value = aa // // 調用API函數獲取數據 // 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ā)送請求的函數 // 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ā)現當滾輪滑到底部時右邊控制臺會打印,沒滑動到底部則不會打印,同時顯示出下邊的顏色
到此這篇關于vue3中使用@vueuse/core中的圖片懶加載案例詳解的文章就介紹到這了,更多相關vue3圖片懶加載內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
一文搞明白vue開發(fā)者vite多環(huán)境配置
Vue是一款流行的JavaScript框架,用于開發(fā)動態(tài)單頁應用程序,本地安裝和環(huán)境配置是學習和使用Vue的第一步,下面這篇文章主要給大家介紹了關于vue開發(fā)者vite多環(huán)境配置的相關資料,需要的朋友可以參考下2023-06-06Vue3 + MybatisPlus實現批量刪除功能(詳細代碼)
這篇文章主要介紹了Vue3 + MybatisPlus實現批量刪除功能,本文通過實例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友參考下吧2024-03-03vue引入elementUi后打開頁面報錯Uncaught?TypeError的解決方式
這篇文章主要給大家介紹了關于vue引入elementUi后打開頁面報錯Uncaught?TypeError:?Cannot?read?properties?of?undefined(reading?‘prototype‘)的解決方式,文中通過圖文介紹的非常詳細,需要的朋友可以參考下2022-08-08