一、传送组件(Teleport组件)
可将组件移动到 DOM 中 Vue app 之外的其他位置,主要是为了解决一些特殊场景下模态对话框组件、组件的渲染。
例子:模拟UI框架对话框组件。
App.vue
<style>
.app{
background-color:gray;
padding:10px;
}
</style>
<template>
<div class="app">
<h3>我是App组件</h3>
<Child/>
</div>
</template>
<script>
import Child from './components/Child'
export default{
name:'App',
components:{
Child
},
}
</script>
Child.vue
<style>
.Child{
background-color:skyblue;
padding:10px;
}
</style>
<template>
<div class="Child">
<h3>我是Child组件</h3>
<Son/>
</div>
</template>
<script>
import Son from './components/Son'
export default{
name:'Child',
components:{
Son
},
}
</script>
Son.vue
<style>
.Son{
background-color:skyblue;
padding:10px;
}
</style>
<template>
<div class="Son">
<h3>我是Son组件</h3>
<Son/>
</div>
</template>
<script>
import Son from './components/Son'
export default{
name:'Son',
components:{
Son
},
}
</script>
Dialog.vue
<style>
.dialog{
position:absolute; //绝对定位
text-align:center;
top:50%;
left:50%;
transform:translate(-50%, -50%)
width:300px;
height:300px;
background:green;
}
.mask{
position:absolute; //绝对定位
top:0;
bottom:0;
left:0;
right:0;
background:rgba(0,0,0,0);
}
</style>
<template>
<div>
<buttuon @click="isShow=true">弹出对话框</button>
<teleport to='body'>
<div class='mask' v-if="isShow">
<div class="dialog">
<h3>我是一个弹窗</h3>
<button @click="isShow=false">关闭弹窗</button>
</div>
</div>
</teleport>
</div>
</template>
<scripct>
import {ref} from 'vue'
export default{
name:'Dialog',
setup(){
let isShow = ref(false)
return {isShow}
}
}
</scripct>
二、Fragment组件
- 在vue2中:组件中必须有一个根标签。
- 在vue3中:组件可以没有根标签,内部会将多个标签包在一个fragment虚拟元素中。
- 好处:减少标签层级,减少内存占用。