1、Teleport
1.1 概念
将组件模版中的指定的dom挂载(传送)到指定的dom元素上,如挂载到body中,挂载到#app选择器上面。
1.2 应用场景
经典案例如:模态框。
<template>
<teleport to="body">
<transition name="dialog-fade">
<div class="dialog-wrapper" v-show="visible">
<div class="dialog">
<div class="dialog-header">
<slot name="title">
<span class="dialog-title">
{{ title }}
</span>
</slot>
</div>
<div class="dialog-body">
<slot></slot>
</div>
<div class="dialog-footer">
<slot name="footer">
<button @click="onClose">关闭</button>
</slot>
</div>
</div>
</div>
</transition>
</teleport>
</template>
<script>
import { defineComponent } from 'vue';
export default defineComponent({
name: 'tdialog'
});
</script>
<script setup>
const props = defineProps({
title: String,
visible: Boolean
});
const emit = defineEmits(['close']);
const onClose = () => {
emit('close');
};
</script>
1.3 用法
- 到标签上
- 到id选择器上
- 到类选择器上
// 渲染到body标签下
<teleport to="body">
<div class="modal">
I'm a teleported modal!
</div>
</teleport>
<teleport to="#some-id" />
<teleport to=".some-class" />
<teleport to="[data-teleport]" />
1.4 为什么要用这个?
比如弹框的显示,一般要左右居中显示在视图中心。但是弹窗的实际代码可能会在某个业务嵌套的div中,当点击按钮显示弹窗的时候,它会以其父级元素居中,而不是以body视图来居中,这时候就可以使用teleport了。
2、Susponse
2.1 概念
等待异步组件时,渲染额外的内容,让应用有更好的额外体验。
2.2 使用
- 异步引入组件
- 使用Suspense包裹好组件,并配置好default与fallback
2.3 为什么?
子组件在异步获取数据的时候,加载页面很慢,设置loading,让应用有更好的额外体验。