vue third-party method useIntersectionObserver implements lazy loading of data

vue third-party method useIntersectionObserver implements lazy loading of data

background

When developing a website, sometimes there will be a lot of data on a page. One-time loading will reduce performance and slow down the loading speed. In fact, just let the data in the visible window be loaded. When part of the page content has not entered the visible area, Sometimes, you don’t need to load data first. Once you enter the visible area, you can listen to the element position through events and then choose the timing of data loading. The advantage of this is that it can enhance performance and avoid unnecessary requests.

There are also third-party methods in the vue project that can help us lazy load data.

Implementation code

@vueuse/coreuseIntersectionObserver Methods  provided for us 

import { useIntersectionObserver } from '@vueuse/core'
import { ref } from 'vue'
export const useLazyData = apiFn => {
  const result = ref([])
  const target = ref(null)
  // 第一个参数:ref引用,获取DOM
  // 第二个参数:回调,回调里面的参数 isIntersecting 会在参数一获取的 DOM 元素进入可视区域的时候监听并且为 true
  // 第三个参数:DOM 元素进入可视区域的距离 从 0 - 1
  const { stop } = useIntersectionObserver(
    target,
    ([{ isIntersecting }]) => {
      if (isIntersecting) {
        stop()
        apiFn().then(data => {
          result.value = data.result
        })
      }
    },
    {
      threshold: 0
    }
  )
  // 返回两个值 result 返回的是调用接口返回的后台的数据
  // target 用来实现 ref 引用
  return { result, target }
}

Export usage  useLazyData method, this method receives one parameter: 接口函数名

Original text: vue third-party method useIntersectionObserver implements lazy loading of data_vue third-party resource lazy loading-CSDN Blog

Guess you like

Origin blog.csdn.net/qq_21473443/article/details/133317058