VUE3 - The use of asynchronous components (21)

Why use async components? Because the previous page loading is when all components are loaded, and then the page is loaded all at once. If the user's network speed is slow, they need to wait for a certain period of time to see things appear on the page. With asynchronous components, we can make the already loaded The completed components appear on the page first, and then use suspenselabels to occupy the space, and use prompt information to occupy the unloaded components, which can improve the user experience, but on March 14, 2022 , the console will still output <Suspense> is an experimental feature and its API will likely change.meaning“<suspend>”是一个实验性功能,其API可能会发生变化。

Parent component App.vue

<template>
  <div>
    <h1>这是父组件</h1>

    <!-- 用suspense包裹异步组件 -->
    <suspense>

      <!-- 组件显示正常时加载 -->
      <template v-slot:default>
        <ChildComponent></ChildComponent>
      </template>

      <!-- 组件显示缓慢时加载 -->
      <template v-slot:fallback>
        <h1>稍等,加载中...</h1>
      </template>

    </suspense>

  </div>
</template>

<script>
// 静态引入
// import ChildComponent from "@/components/ChildComponent";

// 动态引入(异步引入)
import {
     
     defineAsyncComponent} from "vue";
const ChildComponent = defineAsyncComponent(() => import('./components/ChildComponent'))

export default {
     
     
  name: 'App',
  components: {
     
     ChildComponent}
}
</script>

<style>
div {
     
     
  background-color: gray;
  padding: 10px;
}
</style>

Child component ChildComponent.vue

<!-- 此组件保证自身在3秒后才会被成功加载 -->
<template>
  <div>
    <h1>这是子组件</h1>
    <h3>数据:{
   
   { num }}</h3>
  </div>
</template>

<script>
import {
     
     ref} from "vue";

export default {
     
     
  name: "ChildComponent",
  async setup() {
     
      // setup函数可以是async函数,函数的返回可以是一个Promise实例,但需要父组件使用suspense和异步组件的引入

    let num = ref(0)

    const p = new Promise(resolve => {
     
     
      // 设置三秒后调用resolve
      setTimeout(() => {
     
     
        resolve({
     
     num})
      }, 3000)
    })

    const x = await p
    console.log(x) // {num: RefImpl}

    return x // 3秒后await获取Promise对象成功的值,最后返回
  }
}
</script>

<style scoped>
div {
     
     
  background-color: skyblue;
  padding: 10px;
}
</style>

Results display

Guess you like

Origin blog.csdn.net/gty204625782/article/details/123490905