一、<Fragment>
碎片化节点
-
在 vue2 的组件中必须有且只有一个根元素标签,且此标签编译后真实存在 DOM 中,会增加代码体积
-
在 vue3 的组件中可以有多个根元素标签,构建时会生成
<Fragment></Fragment>
标签包裹这些根元素标签,Fragment 标签在编译后不会存在于 DOM 中,即:在 vue3 的组件中可以不用刻意定义根元素标签
<template>
<h1>main</h1>
<h1>content</h1>
</template>
二、<Teleport>
传送门
将其插槽内容渲染到 DOM 中的另一个位置。一般用于将组建挂载到 body 标签下
1. Teleport 的两个属性参数
- to 指定要挂在的位置,值为:css 选择器或 dom 元素
- disabled 是否禁用,值为:布尔值,默认为false不禁用
2. Teleport 的使用
- 将 HomeView 组件通过 Teleport 传送门挂在到 body 下
<template>
<div>
<h1>APP</h1>
<Teleport to="body">
<HomeView />
</Teleport>
</div>
</template>
<script setup>
import HomeView from "@/views/HomeView.vue";
</script>
- 定义 HomeView 组件
<template>
<button @click="open = true">Open Modal</button>
<div v-if="open" class="modal">
<p>Hello from the modal!</p>
<button @click="open = false">Close</button>
</div>
</template>
<script>
export default {
data() {
return {
open: false,
};
},
};
</script>
<style scoped>
.modal {
position: fixed;
z-index: 999;
top: 20%;
left: 50%;
width: 300px;
margin-left: -150px;
}
</style>
网友评论