Suspense:悬疑
首先需要知道异步组件
静态引入:
子组件
<template>
<div class="child">
<h3>我是Child组件</h3>
</div>
</template>
<script>
export default {
name:'Child',
setup(){
}
}
</script>
<style>
.child{
background-color: skyblue;
padding: 10px;
}
</style>
父组件——静态引入,全部完成才能出现
<template>
<div class="app">
<h3>我是App组件</h3>
<Child/>
</div>
</template>
<script>
import Child from './components/Child'//静态引入
export default {
name:'App',
components:{Child},
}
</script>
<style>
.app{
background-color: gray;
padding: 10px;
}
</style>
同时显示
使用异步引入,异步显示——可以根据先后顺序出现,但是用户可能怀疑没有数据 ,需要进行还没有数据的判断
<script>
import {defineAsyncComponent} from 'vue'
const Child = defineAsyncComponent(()=>import('./components/Child')) //异步引入
export default {
name:'App',
components:{Child},
}
</script>
使用Suspense包裹组件,并配置好default 与 fallback
<template>
<div class="app">
<h3>我是App组件</h3>
<Suspense>
放置本应该展示的组件
<template v-slot:default>
<Child/>
</template>
消息没有回来的时候展示的信息
<template v-slot:fallback>
<h3>稍等,加载中...</h3>
</template>
</Suspense>
</div>
使用了Suspense并且组件是异步引入,就可以使用Promise,作为返回值
<template>
<div class="child">
<h3>我是Child组件</h3>
{{sum}}
</div>
</template>
<script>
import {ref} from 'vue'
export default {
name:'Child',
setup(){
let sum = ref(0)
let p = new Promise((resolve,reject)=>{
setTimeout(()=>{
resolve({sum})
},3000)
})
return p
}
}
</script>
<style>
.child{
background-color: skyblue;
padding: 10px;
}
</style>
import {ref} from 'vue'
export default {
name:'Child',
async setup(){
let sum = ref(0)
let p = new Promise((resolve,reject)=>{
setTimeout(()=>{
resolve({sum})
},3000)
})
//await 等待p成功的结果 配合async
return await p
}
}
setup不能是一个async函数,因为返回值不再是return的对象, 而是promise, 模板看不到return对象中的属性。(后期也可以返回一个Promise实例,但需要Suspense和异步组件的配合)