Make writing a habit together! This is the 11th day of my participation in the “Gold Digging Day New Plan · April More text Challenge”. Click here for more details.

Nuxt3- Learning path 11, Components – Dynamic loading and lazy loading

The introduction

This series will introduce and begin learning about Nuxt3 with my understanding.

The middle will insert their own links to the messy knowledge points.

component

Nuxt3’s component concept is similar to that of Vue, but Nuxt3 also has one big feature: lazy loading.

Lazy loading

I believe that lazy loading is no stranger to everyone, and it is one of the most reliable helpers of our performance optimization.

But what is the lazy loading of Nuxt3 components? Is there really lazy loading?

Here’s the official code

<template>
  <div>
    <h1>Mountains</h1>
    <LazyMountainsList v-if="show" />
    <button v-if=! "" show" @click="show = true">Show List</button>
  </div>
</template>

<script>
export default {
  data() {
    return {
      show: false}}}</script>
Copy the code

Can you see lazy loading from here?

It doesn’t feel exactly the way I thought it would. This is v-if to control a rendering of the component acridine

The lazy loading of Nuxt3 components is not quite understood, and students who can also hope to give a good answer.

Dynamic loading

Dynamic loading of components, this is very useful. The usage is similar to that of dynamic components in Vue3.

Vue3 provides an Api called resolveComponent to import a component and assign it to a variable.

const TheHeader = resolveComponent('TheHeader')
const TheHeader = resolveComponent('the-header')
Copy the code

Note that the naming is strict, recommended to use the above, more secure, not easy to make mistakes.

Load the component dynamically with < Component :is=” XXX “/>.

Add the code directly to the default.vue page

<template>
    <div>
      <h2>Using dynamic loading</h2>
      <button @click="onChange">switch</button>
      <component :is="currentComponent" />
    </div>
</template>
<script setup>
    const TheHeader = resolveComponent('TheHeader')
    const TheFooter = resolveComponent('TheFooter')

    const flag = ref(false)
    const currentComponent = shallowRef(TheHeader)

    const onChange = () = >{ flag.value = ! flag.value currentComponent.value = flag.value ? TheHeader : TheFooter }</script>
Copy the code

So here you can see that I’m using a shallowRef, and I started with a ref, but it’s not recommended, so I’m using the shallowRef API.

The whole point of the code is to display TheHeader component by default, but change it by clicking the toggle button. Adapt the component TheFooter. Control is carried out through the variable flag

Click the toggle button

conclusion

Learn Nuxt3 components – dynamic components and lazy loading. This allows us to have more flexibility to control the use of different components on the page, improve the efficiency of development, and deal with complex interaction scenarios.