概述
为什么要使用异步组件?因为以前页面的加载是当所有组件加载完毕,然后页面一下子全部加载,如果用户网速慢的话就需要等待一定的时间才能看到东西出现在页面,有了异步组件后,我们可以让已经加载完的组件先出现在页面,然后用
suspense
标签以占位,用提示信息占位还没加载的组件,这样可以改善用户体验,但是在2022年3月14日时,控制台还是会输出<Suspense> is an experimental feature and its API will likely change.
意思是“<suspend>”是一个实验性功能,其API可能会发生变化。
文章目录
- 父组件App.vue
- 子组件ChildComponent.vue
- 结果展示
父组件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>
子组件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>
结果展示
最后
以上就是热情绿草为你收集整理的VUE3-异步组件的使用(21)的全部内容,希望文章能够帮你解决VUE3-异步组件的使用(21)所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复