Simple implementation of lazy loading of component data

VueUse component data lazy loading

1. Understanding

Objective of this section: to understand what component data lazy loading means from a practical point of view
Think about two questions

  1. Where are our general data requests initiated?
  2. What are the characteristics of life cycle hook function?

At present, ajax requests in each component are generally initiated in the created hook function or mounted hook function. The life cycle has one feature: it is automatically executed following the initialization process of the component, which is beyond the control of the developer. Therefore, the requests in popular recommendation / fresh good items and other modules on the home page will be initiated once the component renders the ajax request, The home page of e-commerce is usually very long, and some module components will not even appear in the viewport. Such mindless loading of data is obviously unreasonable and wasteful. In order to solve this problem, we have introduced lazy loading of component array

Conclusion (what is lazy loading of component data?)

Only when the component officially enters the viewport can the ajax request inside the component be initiated, otherwise no data will be requested

2. How to achieve

Objective of this section: learn how to know through technical means that the component enters the viewport

Technical proposal:

We can use useIntersectionObserver in @ vueuse/core to monitor the behavior of components entering the visual area, which needs to cooperate with vue3 0 can only be realized by combining API s
useIntersectionObserver Link address

  1. Download the VueUse plug-in
yarn add @vueuse/core
  1. Use the methods in the useIntersectionObserver plug-in
import { useIntersectionObserver } from '@vueuse/core'
  1. First analyze the useIntersectionObserver function:
const { stop } = useIntersectionObserver(
  target,
  ([{ isIntersecting }], observerElement) => {
    targetIsVisible.value = isIntersecting
  },
)
/*
  1.stop An executable function to stop listening
  2.target A RefImpl object formed after the ref api call can also be a dom object
  3.isIntersecting A data type of Boolean value is true when the monitored element enters the viewport area and false when it leaves the viewport area
*/
  1. Let's take a module as an example to demonstrate the use of this function

HomePanel is a component, which can be replaced with its own component when in use

<HomePanel 
  ref="target" 
></HomePanel>

<script>
export default {
  name: 'HomeHot',
  components: { HomePanel },
  setup () {
  	// Array for storing data
    const list = ref([])
    // Request data function
    const getList = () => {
      const res = await findHot()
      list.value = res.data.result
    }
    // Gets the DOM node of the
    const target = ref(null)
     // Stop is an executable method, and the call will stop listening
    // The callback function is no longer executed whether the element enters or leaves the viewport area
    // Note: you will not only listen once, but only enter or leave the viewport callback function will be executed
    const { stop } = useIntersectionObserver(
      // Target is the dom container of the observation target. It must be a dom container and vue3 dom object bound in 0 mode
      target,
      // isIntersecting whether to enter the visual area. true is to enter and false is to move out
      // Observer element the dom to be observed
      ([{ isIntersecting }], observerElement) => {
        // You can judge here according to the business
        if (isIntersecting) {
          // Stop listening to prevent calling the interface repeatedly
          stop()
          console.log('Formally initiate interface request')
          getList()
        }
      }
    )
    return {
      target,
      goodsRef
    }
}
</script>

3. Package into functions that can realize the reuse of basic business logic

Encapsulate into function

// Introducing useIntersectionObserver
import { useIntersectionObserver } from '@vueuse/core'
import { ref } from 'vue'

export const useObserver = apiFn => {
  // Gets the DOM node of the
  const target = ref(null)
  // Stop is an executable method, and the call will stop listening
  // The callback function is no longer executed whether the element enters or leaves the viewport area
  // Note: you will not only listen once, but only enter or leave the viewport callback function will be executed
  const { stop } = useIntersectionObserver(
    //  //Target is the dom container of the observation target. It must be a dom container and vue3 dom object bound in 0 mode
    target,
    ([{ isIntersecting }], observerElement) => {
      /**
       *  isIntersecting Whether to enter the visual area. true means to enter and false means to move out
       *  observerElement Observed dom
       *  Here, you can judge according to isIntersecting, and then do business
       */
      if (isIntersecting) {
        // Launch Axios request here
        apiFn()
        // Stop listening to prevent calling the interface repeatedly
        stop()
      }
    }
  )

  return target
}

Detection function effect

<HomePanel 
  ref="target" 
></HomePanel>

<script>
// Introduction function
import { useObserver } from '@/compositions'

export default {
  name: 'HomeHot',
  components: { HomePanel },
  setup () {
  	// Array for storing data
    const list = ref([])
    // Request data function
    const getList = () => {
      const res = await findHot()
      list.value = res.data.result
    }
    // The return value of the calling function is obtained. It is used on the Dom node, so return it
    const target = useObserver(getNewGoods)

    return {
      goods,
      target
    }
  }
}
</script>

The above code is based on the original encapsulation function and can meet most business logic implementations

Keywords: Javascript Front-end ECMAScript Vue Vue.js

Added by idealbrain on Sat, 12 Feb 2022 02:22:12 +0200