Vue3 内置组件Teleport以及Susponse

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,让应用有更好的额外体验。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值