Data lazy loading is an inevitable problem to solve and what methods does Vue3 provide to solve it

use@vueuse/coreIn theuseIntersectionObserverTo realize the monitoring into the visual area behavior, with vue3.0 combination of THE WAY to achieve the API.

  • This is auseIntersectionObserverFunction:
Const {stop} = useIntersectionObserver(target, fn, options) const {stop} = useIntersectionObserver(target, fn, options) // The first parameter of the callback function isIntersecting indicates that the monitored element has entered the viewable area. // The first parameter of the callback function isIntersecting indicates that the monitored element has entered the viewable area. // The configuration option // Stop is to stop observing whether to enter or move out of the viewable area UseIntersectionObserver (target is the target DOM container to be observed, and it must be a DOM container and a TARGET of the DOM object bound by Vue3.0. // DOM ([{isIntersecting}], observerElement) => {// It can be judged by isIntersecting. Then do business},)Copy the code

Specific steps

1.1 This is specific implementation code can be packaged into a separate file when needed directly imported

Import {ref} from 'vue' import {useIntersectionObserver} from '@vueuse/core' // Package a Hook method to implement lazy loading of export const data UseLazyData = (apiFn) => {// The interface is invoked when the current component enters the viewport // the DOM element that is being listening to is const target = ref(null) // The result obtained by the interface is const result = ref([])  const { stop } = useIntersectionObserver(target, ([{isIntersecting}]) => {if (isIntersecting) {// Enter the visible area apiFn(). Then (data => {result.value = data.result}) // Stop listening stop() } }) return { result, target } }Copy the code

2. Use the required components directly

  • Which part do I need to add oneref="target"

  • Import that fileimport { useLazyData } from '@/hook'
  • Direct use of

2.1 There is a small problem:

If the area of the component that needs lazy loading is large, the page needs to scroll more area before loading data, which is not good.

2.2 reasons:

By default, useIntersectionObserver judges whether to enter the intersectionObserver based on the area of the viewing port taking up 0.1 of the total element area. However, the default ratio of 0.1 will cause this problem when the element is large: it seems to be visible, but our callback is not executed.

2.2 to solve:

Add a parameter: threshold, the proportion of the cross between the container and the visible area (the area entered/the complete area of the container), which is directly set to 0

 const { stop } = useIntersectionObserver(
    target,
    ([{ isIntersecting }]) => {
      if (isIntersecting) {
        stop()
        apiFn()
      }
    },
    { threshold: 0}
  )
  return { result, target }
}
Copy the code