vue3 - (数据懒加载)监听元素是否进入可视区域
时间: 2023-12-08 14:03:17 浏览: 71
在 Vue3 中,可以使用 Intersection Observer API 监听元素是否进入可视区域,实现数据懒加载。
具体实现步骤如下:
1. 在需要监听的元素上使用 ref 获取 DOM 元素的引用。
2. 在组件的 `setup` 函数中,使用 `onMounted` 钩子函数创建一个 IntersectionObserver 对象,并设置回调函数。
```javascript
import { onMounted } from 'vue';
export default {
setup() {
const targetEl = ref(null);
onMounted(() => {
const observer = new IntersectionObserver(entries => {
if (entries[0].isIntersecting) {
// 元素进入可视区域时执行的操作,比如加载数据
}
});
observer.observe(targetEl.value);
});
return {
targetEl
};
}
}
```
3. 在模板中将 ref 对象绑定到需要监听的元素上。
```html
<template>
<div ref="targetEl"></div>
</template>
```
这样,当元素进入可视区域时,IntersectionObserver 对象会调用回调函数,从而触发数据的懒加载。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)