Skip to content

Vue3中新的组件

1. Fragment组件

  • 在Vue2中:组件必须有一个根标签
  • 在Vue3中: 组件可以没有根标签,Vue内部会将多个标签包含在一个Fragment虚拟元素中
  • 好处是:减少标签层级,减少内存占用

提示

Vue3内部为我们的组件套上Fragment标签,因此我们不再必须有一个根标签,我们也不必手动编写,Vue3自动维护Fragment

2. Teleport组件

  • 什么是teleport组件?
    Teleport是一种能够将我们的组件html结构移动到指定位置的技术。

手搓一个弹出模态框:

vue
<template>
  <!-- to属性可以是body,可以是index.html里面的id属性 -->
  <Teleport to="dialogNode">
    <div v-show="showFlag" class="mask">
    <div class="dialog">
      <h3>我是标题</h3>
      <ul>
        <li>我是内容</li>
        <li>我是内容</li>
        <li>我是内容</li>
      </ul>
      <button @click="closeDialog">关闭弹窗</button>
    </div>
  </div>
  </Teleport>
</template>

<script setup name="UserDialog">
import { ref, reactive, defineExpose } from 'vue'
let showFlag = ref(false)
let closeDialog = (() => {
  showFlag.value = false
})
// 允许外部访问的数据暴露出去
defineExpose({
  showFlag
})
</script>
<style scoped>
.mask {
  /* 半透明 */
  background-color: rgb(0, 0, 0, 0.5);
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
}
.dialog {
  text-align: center;
  position: absolute;
  /* top,left相对父元素 */
  top: 50%;
  left: 50%;
  /* 相对自己 */
  transform: translate(-50%, -50%);
  width: 400px;
  height: 300px;
  background-color: green;
}</style>
vue
<template>
  <div>
    <button @click="showDialog">打开弹窗</button>
    <br />
    <UserDialog ref="diglogRef"></UserDialog>
  </div>
</template>

<script setup>
  import UserDialog from './components/UserDialog.vue'
  import { ref, reactive, onMounted } from 'vue'
  // 拿到子组件
  const diglogRef = ref()
  
  let showDialog = () => {
    // 拿到子组件的值showFlag并修改
    diglogRef.value.showFlag = true
  }
</script>

2. Suspense组件

  • 等待异步组件时渲染一些额外内容,让应用有更好的用户体验
  • 使用步骤:
    • 异步导入组件
    • 使用Suspense包裹组件,并配置default与fallback
js
<template>
  <h2>我是父组件</h2>
  <div>
    <Suspense>
      <template v-slot:default>
        <Test></Test>
      </template>
      <template v-slot:fallback>
        <h2>请稍后。。。</h2>
      </template>
    </Suspense>
  </div>
</template>

<script setup>
  // import Test from './components/Test.vue' // 静态导入
  // 异步导入
  import { ref, defineAsyncComponent } from 'vue'
  const Test = defineAsyncComponent(()=>import('./components/Test.vue'))
 
</script>

运行效果: Alt text 不过官方提示Suspense还是处于实验阶段: Alt text