vue3数据懒加载方法封装
// hooks 封装逻辑,提供响应式数据。
import { useIntersectionObserver } from '@vueuse/core'
import { ref } from 'vue'
/**
* 数据懒加载函数
* @param {被观察的对象} target
* @param {不同的API函数} apiFn
*/
export const useLazyData = (apiFn) => {
const target = ref(null)
const { stop } = useIntersectionObserver(
// target 是观察的目标dom容器,必须是dom容器,而且是vue3.0方式绑定的dom对象
target,
// isIntersecting 是否进入可视区域,true是进入 false是移出
// observerElement 被观察的dom
([{ isIntersecting }], observerElement) => {
// 在此处可根据isIntersecting来判断,然后做业务
if (isIntersecting) {
// stop 是停止观察是否进入或移出可视区域的行为
stop()
// 调用 api 函数
apiFn().then(data => {
result.value = data.result
})
}
},
{
// threshold 容器和可视区交叉的占比(进入的面积/容器完整面试) 取值,0-1 之间,默认比0大,所以需要滚动较多才能触发进入可视区域事件。
threshold: 0
}
)
// 返回数据
return { result, target }
}