vue3 - (数据懒加载)监听元素是否进入可视区域

403 阅读2分钟
组件数据懒加载

我们可以使用 @vueuse/core中的 useIntersectionObserver 来实现监听进入可视区域行为,但是必须配合vue3.0的组合API的方式才能实现。

大致步骤:

理解useIntersectionObserver 的使用,各个参数的含义
改造 组件成为数据懒加载,掌握 useIntersectionObserver函数的用法
封装 useLazyData函数,作为数据懒加载公用函数
使用懒加载方式
先分析下这个useIntersectionObserver 函数:

// stop 是停止观察是否进入或移出可视区域的行为    
const { stop } = useIntersectionObserver(
  // target 是观察的目标dom容器,必须是dom容器,而且是vue3.0方式绑定的dom对象
  target,
  // isIntersecting 是否进入可视区域,true是进入 false是移出
  // observerElement 被观察的dom
  ([{ isIntersecting }], observerElement) => {
    // 在此处可根据isIntersecting来判断,然后做业务
  },
)
简单案例代码
<template>
  <div class="box">
    第一个盒子
  </div>
  <!-- 要检测的元素添加个名字 -->
  <div class="box" ref="target">
    第二个盒子
  </div>
</template>

<script>
// useIntersectionObserver 检测目标元素的可见性。
import { ref } from 'vue'
import { useIntersectionObserver } from '@vueuse/core'
export default {
  setup () {
    const target = ref(null)
    // stop             用于停止检测函数
    // target           被检测的元素
    // isIntersecting   布尔值,元素是否可见 true/false
    const { stop } = useIntersectionObserver(
      target,
      ([{ isIntersecting }], observerElement) => {
        // 如果元素可以,发送请求获取数据,并停止检测避免重复发送请求
        if (isIntersecting) {
          console.log('isIntersecting元素可见性,发送请求获取数据', isIntersecting)
          stop()
        }
      }
    )
    return { target }
  }
}
</script>

<style lang="less" scoped>
.box {
  width: 1000px;
  height: 200px;
  background-color: pink;
  margin: 500px auto;
}
</style>
封装懒加载数据组件

实现当组件进入可视区域在加载数据。
由于数据加载都需要实现懒数据加载,所以封装一个钩子函数,得到数据。

src/hooks/index.js

// hooks(钩子)封装逻辑,提供响应式数据。
import { ref } from 'vue'
import { useIntersectionObserver } from '@vueuse/core'

// 数据懒加载函数
export const useLazyData = (apiFn) => {
  // 1. 被观察的对象
  const target = ref(null)
  // 2. 用于存放后台数据的变量
  const list = ref([])
  // stop             用于停止检测函数
  // target           被检测的元素
  // isIntersecting   布尔值,元素是否可见 true/false
  const { stop } = useIntersectionObserver(
    target,
    ([{ isIntersecting }]) => {
      // 如果元素可以,发送请求获取数据,并停止检测避免重复发送请求
      if (isIntersecting) {
        console.log(target.value, '元素可见可以发请求了.....')
        // 调用 API 获取数据
        apiFn().then(({ result }) => {
          list.value = result
        })
        stop()
      }
    }
  )
  // 钩子函数返回---> 响应式数据(目标元素, 后台数据)
  return { list, target }
}