vue3.0(十五)内置组件Teleport和Suspense


一、Teleport

<Teleport> 是一个内置组件,它可以将一个组件内部的一部分模板“传送”到该组件的 DOM 结构外层的位置去。

1.基本用法

  1. Props

    interface TeleportProps {
      /**
       * 必填项。指定目标容器。
       * 可以是选择器或实际元素。
       */
      to: string | HTMLElement
      /**
       * 当值为 `true` 时,内容将保留在其原始位置
       * 而不是移动到目标容器中。
       * 可以动态更改。
       */
      disabled?: boolean
    }
    
  2. 使用语法

    <teleport to="body">
        <div>
       需要创建的内容
      </div>  
    </teleport>
    
  3. to 属性是指定 teleport 中的内容 加入的DOM元素。可以是标签名,也可以是 id 或类名。

    //标签名  。上述实例就是加入body元素内,使用的是标签名。
    <teleport to="body"></teleport>
    
    //类名。如:to=".className"
    <teleport to=".className"></teleport>
    
    //id名
    <teleport to="#idName"></teleport>
    
  4. 示例

    <template>
      <div>
        <div id="idName">111</div>
        <div class="className">222</div>
    
        <!-- //标签名  。上述实例就是加入body元素内,使用的是标签名。 -->
        <Teleport to="body">
          <div>我是标签名body</div>
        </Teleport>
        
        <!-- //类名。如:to=".className" -->
        <Teleport v-if="flag" to=".className">
          <div>
            我是类名className
          </div>
        </Teleport>
        
        <!-- //id名 -->
        <Teleport v-if="flag" to="#idName">
          <div>
            我是id名idName
          </div>
        </Teleport>
      </div>
    </template>
    <script lang="ts">
    import { defineComponent, ref, onMounted } from 'vue'
    export default defineComponent({
      setup () {
        const flag = ref(false)
        onMounted(() => {
          flag.value = true
        })
        return {
          flag
        }
      }
    })
    </script>
    

    在这里插入图片描述

  5. bug解决, 一定要用v-if控制Teleport 组件,确保它在onMounted加载完成之后传送。如果不加会报错:

    解决办法
    确保目标元素存在于DOM中,并且具有正确的类名".modal"。
    确保组件在DOM树中的位置正确,确保它在目标元素之后被渲染。
    如果使用了Vue的单文件组件,请确保的父组件已经被正确渲染。
    如果目标元素是动态创建的,请确保在查找目标元素之前,该元素已经被创建。

2.禁用Teleport

<Teleport> 动态地传入一个 disabled

当值为 true 时,内容将保留在其原始位置
而不是移动到目标容器中。
可以动态更改。

<template>
  <div>
    <div class="className">222 {{ isMobile }}</div>
    <div id="idName">111 {{ !isMobile }}</div>

    <!-- //标签名  。上述实例就是加入body元素内,使用的是标签名。 -->
    <Teleport to="body" :disabled="false">
      <div>我是标签名body</div>
    </Teleport>
    
    <!-- //类名。如:to=".className" -->
    <Teleport :disabled="isMobile" v-if="flag" to=".className">
      <div>
        我是类名className
      </div>
    </Teleport>
    
    <!-- //id名 -->
     <div v-if="flag">
       <Teleport :disabled="false" to="#idName">
         <div>
           我是id名idName
         </div>
       </Teleport>
     </div>
  </div>
</template>
<script lang="ts">
import { defineComponent, ref, onMounted } from 'vue'
export default defineComponent({
  setup () {
    const flag = ref(false)
    const isMobile = ref(false)
    const isId = ref(false)
    function getIsMobile () {
      const isMobi = navigator.userAgent.toLowerCase().match(/(ipod|ipad|iphone|android|coolpad|mmp|smartphone|midp|wap|xoom|symbian|j2me|blackberry|wince)/i) != null
      console.log(isMobi)
      if (isMobi) {
        isMobile.value = true
      } else {
        isMobile.value = false
      }
    }
    onMounted(() => {
      flag.value = true
      getIsMobile()
    })
    return {
      flag,
      isMobile,
      isId
    }
  }
})
</script>

在这里插入图片描述

3.多个 Teleport 共享目标

一个可重用的模态框组件可能同时存在多个实例。
多个 <Teleport> 组件可以将其内容挂载在同一个目标元素上,而顺序就是简单的顺次追加,后挂载的将排在目标元素下更后面的位置上。

<template>
  <div>
    <div class="className">222 {{ isMobile }}</div>
    <div id="idName">111 {{ !isMobile }}</div>

    <!-- //标签名  。上述实例就是加入body元素内,使用的是标签名。 -->
    <Teleport to="body" :disabled="false">
      <div>我是标签名body</div>
    </Teleport>
    
    <!-- //类名。如:to=".className" -->
    <Teleport :disabled="isMobile" v-if="flag" to=".className">
      <div>
        我是类名className1
      </div>
    </Teleport>
    <Teleport :disabled="isMobile" v-if="flag" to=".className">
      <div>
        我是类名className2
      </div>
    </Teleport>
    <Teleport :disabled="isMobile" v-if="flag" to=".className">
      <div>
        我是类名className3
      </div>
    </Teleport>
    <Teleport :disabled="isMobile" v-if="flag" to=".className">
      <div>
        我是类名className4
      </div>
    </Teleport>
    
    <!-- //id名 -->
     <div v-if="flag">
       <Teleport :disabled="false" to="#idName">
         <div>
           我是id名idName
         </div>
       </Teleport>
     </div>
  </div>
</template>
<script lang="ts">
import { defineComponent, ref, onMounted } from 'vue'
export default defineComponent({
  setup () {
    const flag = ref(false)
    const isMobile = ref(false)
    const isId = ref(false)
    function getIsMobile () {
      const isMobi = navigator.userAgent.toLowerCase().match(/(ipod|ipad|iphone|android|coolpad|mmp|smartphone|midp|wap|xoom|symbian|j2me|blackberry|wince)/i) != null
      console.log(isMobi)
      if (isMobi) {
        isMobile.value = true
      } else {
        isMobile.value = false
      }
    }
    onMounted(() => {
      flag.value = true
      getIsMobile()
    })
    return {
      flag,
      isMobile,
      isId
    }
  }
})
</script>

在这里插入图片描述

4.搭配组件

<Teleport> 只改变了渲染的 DOM 结构,它不会影响组件间的逻辑关系。也就是说,如果 <Teleport> 包含了一个组件,那么该组件始终和这个使用了 <teleport> 的组件保持逻辑上的父子关系。传入的 props 和触发的事件也会照常工作。
这就说明来自父组件的注入也会按预期工作,子组件将在 Vue Devtools 中嵌套在父级组件下面,而不是放在实际内容移动到的地方。

二、 Suspense

<Suspense> 是一个内置组件,用来在组件树中协调对异步依赖的处理。它可以在组件树上层等待下层的多个嵌套异步依赖项解析完成,并可以在等待时渲染一个加载状态。

用于协调对组件树中嵌套的异步依赖的处理。

注:<Suspense>是一项实验性功能。它不一定会最终成为稳定功能,并且在稳定之前相关 API 也可能会发生变化。

1.什么是Suspense

Suspense 是一个用于处理异步操作(如数据加载)的特性,在 Vue 3 中引入,旨在改善用户体验。它允许您在异步操作完成之前显示占位内容,以防止页面出现空白或加载指示器。一旦异步操作完成,Suspense 将自动切换到实际内容,提供了更好的用户体验。

interface SuspenseProps {
  timeout?: string | number
  suspensible?: boolean
}
  1. Suspense 主要用于以下情况:
  • 异步组件加载:当您的应用需要在渲染组件之前等待异步组件加载完成时,可以使用 Suspense。
  • 数据加载:当您需要等待异步数据加载完成后再渲染组件,以避免渲染空白或加载指示器时,可以使用

2.异步依赖

Suspense 最常用于处理异步组件加载。Vue 3 允许您按需加载组件,以减小应用的初始加载时间。以下是一个示例,展示了如何使用 Suspense 处理异步组件加载:

  <Suspense>
    <template #default>
      <AsyncComponent />
    </template>
 
    <template #fallback>
      <LoadingIndicator />
    </template>
  </Suspense>
</template>
 
<script>
import { defineAsyncComponent } from 'vue';
 
const AsyncComponent = defineAsyncComponent(() =>
  import('./AsyncComponent.vue')
);
 
export default {
  components: {
    AsyncComponent
  }
};
</script>在这里插入代码片

<Suspense> 可以等待的异步依赖有两种:

  • 带有异步 setup() 钩子的组件。这也包含了使用 <script setup> 时有顶层 await 表达式的组件。
  • 异步组件。

3.加载中状态

<Suspense> 组件有两个插槽:#default 和 #fallback。两个插槽都只允许一个直接子节点。在可能的时候都将显示默认槽中的节点。否则将显示后备槽中的节点。
当要加载的组件不满足状态时,Suspense 将回退到 fallback状态一直到加载的组件满足条件,才会进行渲染。

<template>
  <Suspense>
    <template #default>
      <UserData :user-id="userId" />
    </template>

    <template #fallback>
      <LoadingIndicator />
    </template>
  </Suspense>
</template>

4.事件

<Suspense> 组件会触发三个事件:pending、resolve 和 fallback。

  1. pending 事件是在进入挂起状态时触发。
  2. resolve 事件是在
  3. default 插槽完成获取新内容时触发。
  4. fallback 事件则是在 fallback 插槽的内容显示时触发

5.错误处理

<Suspense> 组件自身目前还不提供错误处理,不过可以使用 errorCaptured 选项或者 onErrorCaptured() 钩子,在使用到 <Suspense> 的父组件中捕获和处理异步错误。

<template>
  <div>
    <h1>标题</h1>
    <suspense>
      <template #default>
        <async-component />
      </template>
      <template #fallback>
        <div>加载中...</div>
      </template>
      <template #error="error">
        <div>加载出错:{{ error }}</div>
      </template>
    </suspense>
  </div>
</template>

<script>
import { defineAsyncComponent } from 'vue';

const AsyncComponent = defineAsyncComponent(() =>
  import('./AsyncComponent.vue')
);

export default {
  components: {
    AsyncComponent
  }
};
</script>

6.和其他组件结合

<Suspense><Transition><KeepAlive> 等组件结合。要保证这些组件都能正常工作,嵌套的顺序非常重要。
<Suspense><Transition><KeepAlive> 组件都通常与 Vue Router 中的 <RouterView> 组件结合使用。

<RouterView v-slot="{ Component }">
  <template v-if="Component">
    <Transition mode="out-in">
      <KeepAlive>
        <Suspense>
          <!-- 主要内容 -->
          <component :is="Component"></component>

          <!-- 加载中状态 -->
          <template #fallback>
            正在加载...
          </template>
        </Suspense>
      </KeepAlive>
    </Transition>
  </template>
</RouterView>

Vue Router 使用动态导入对懒加载组件进行了内置支持。这些与异步组件不同,目前他们不会触发 <Suspense>。但是,它们仍然可以有异步组件作为后代,这些组件可以照常触发 <Suspense>

注意

  1. Suspense 组件必须包裹需要异步加载的组件。
  2. 需要定义 fallback 模板,用于在异步组件加载完成前展示 Loading 状态。
  3. 可以使用 Teleport 元素将组件渲染到指定的 DOM 节点中。
  4. 需要根据具体情况,结合 Vue Router 和 Vuex 构建完整的异步组件加载方案。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值