1.新建hooks/index.js
import { useIntersectionObserver } from '@vueuse/core'
import { ref } from 'vue'
/**
* 用于懒加载数据
* @param {*} apiFn 懒加载数据的接口
* @returns target: 需要绑定的DOM对象 result: 结果数据
*/
export const useLazyData = (apiFn) => {
// 需要
// 1. 被观察的对象
// 2. 不同的API函数
const target = ref(null)
const result = ref([])
const { stop } = useIntersectionObserver(
target,
([{ isIntersecting }], observerElement) => {
if (isIntersecting) {
stop()
// 调用API获取数据
apiFn().then(data => {
result.value = data.result
})
}
}
)
// 返回--->数据(dom,后台数据)
return { target, result }
}
2.具体使用,需要判断哪个div就在其身上绑定ref="target"
3.效果