1.作用:suspense在等待异步组件时额外渲染一些内容,使用户拥有更好的体验。
2.使用:
引入异步组件,Child需要在components里注册
import {defineAsyncComponent} from 'vue'
// import demo from './components/demo.vue' //静态引入
const Child = defineAsyncComponent(()=>import('./components/demo.vue'))//动态引入
使用susoense包裹组件,并配置好default和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>
这是我子组件里面写的内容,方便查看效果
<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>
看看效果:
子组件在等待结果的时候会先渲染fallback里面的内容