Skip to main content

数据懒加载

数据懒加载

Vue3组件数据懒加载

5 人赞同了该文章

  • 单张页面数据较多时,可以使用组件数据懒加载,减少网络请求,提高页面的响应速度。
  • 安装npm i @vueuse/core -S 库,用到其中的 useIntersectionObserver 来实现监听进入可视区域行为,配合 vue3.0 的组合 API 的方式实现。
  • 封装方法 index.js
//提供复用逻辑
import { useIntersectionObserver } from "@vueuse/core"
import { ref } from 'vue'
// 数据懒加载函数
// target 要监听的 Dom 对象
// apiFn API函数
export const useLazyData = (apiFn) => {
const result = ref([])
const target=ref(null)

const { stop } =useIntersectionObserver(
target,
([{ isIntersecting }], observerElement) => {
console.log(observerElement);
//isIntersecting是否进入可视区
if (isIntersecting) {
stop()//停止观察
//调用api函数获取数据
apiFn().then(data => {
result.value=data
})
}
},
// 配置选项
{
threshold:0 //冒出之后就触发
}
)
return {result,target}
}
  1. 调用方法 导入封装的 index.js 文件 import { useLazyData } from 'index.js'
  2. 在需要懒加载数据的组件上加入 ref <myComponent ref='target' />
setup(){     
const { target,result } =useLazyData( FnApi ) //FnApi 请求函数
return { target , result }
}