The use of suspense in vue3

1. Function: suspense renders some additional content while waiting for asynchronous components, so that users have a better experience.

2. Use:

 To introduce asynchronous components, Child needs to be registered in components
import {defineAsyncComponent} from 'vue' 
// import demo from './components/demo.vue' //静态引入
const Child = defineAsyncComponent(()=>import('./components/demo.vue'))//动态引入
Use susoense to wrap components and configure default and fallback
<template>
  <!-- vue3中模版结构可以没有根标签 -->
  <div class="father">
    <div class="child">
      <teleport to='body'>
        <input type="text" v-model="keyword">
        <h3>{
   
   {keyword}}</h3>
      </teleport>
    </div>
    <Suspense>
      <!-- v-slot:default,默认要渲染的组件 -->
      <template v-slot:default>
        <Child></Child>
      </template>
      <!-- v-slot:fallback里面写组件加载过程中需要显示的内容 -->
      <template v-slot:fallback>
        <div>
          <h3>加载中,请稍等。。。</h3>
        </div>
      </template>
    </Suspense>
  </div>
</template>

This is the content written in my subcomponent, which is convenient to view the effect

<template>
  <div class="child">
    <div>我是子组件</div>
    <h3>{
   
   {sum}}</h3>
  </div>
</template>

<script>
import { ref } from "vue";
export default {
  name: "HelloWorld",
  props: {
    msg: String,
  },
  setup() {
    const sum = ref(0);
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        resolve(sum);
      }, 3000);
      if (sum.value != 0) {
        setTimeout(() => {
          reject(sum);
        }, 3000);
      }
    });
  },
};
</script>
<style scoped>
.child {
  padding: 10px;
  background-color: #e8f;
}
</style> 

Take a look at the effect:

When the child component is waiting for the result, it will first render the content in the fallback

Acho que você gosta

Origin blog.csdn.net/weixin_53841730/article/details/130261265
Recomendado
Clasificación