teleport
,是传送的意思。
看个具体的例子吧。项目目录如下。
- main.js
import { createApp } from 'vue'
import App from './App.vue'
createApp(App).mount('#app')
- 祖组件App.vue
<template>
<div class="app">
<h2>我是App组件</h2>
<Son/>
</div>
</template>
<script>
import Son from "./components/Son.vue";
export default {
name:"App",
components:{Son}
}
</script>
<style>
.app{
background: gray;
padding: 10px;
}
</style>
- 子组件Son.vue
<template>
<div class="son">
<h2>我是Son组件</h2>
<Grandson/>
</div>
</template>
<script>
import Grandson from "./Grandson.vue";
export default {
name:"Son",
components:{Grandson}
}
</script>
<style scoped>
.son{
background: skyblue;
padding: 10px;
}
</style>
- 孙组件Grandson.vue
<template>
<div class="grandson">
<h2>我是Grandson组件</h2>
<Dialog/>
</div>
</template>
<script>
import Dialog from "./Dialog.vue";
export default {
name:"Grandson",
components:{
Dialog
}
}
</script>
<style scoped>
.grandson{
background: orange;
padding: 10px;
}
</style>
- 对话框组件Dialog.vue
<template>
<button @click="isShow = true">打开对话框</button>
<div v-if="isShow" class="mask">
<div class="dialog">
<div class="header">
<span class="title">温馨提示</span>
<button @click="isShow = false">关闭对话框</button>
</div>
<div class="content">
今日春分。
春色从此分,春意就此浓。
</div>
</div>
</div>
</template>
<script>
import {ref} from "vue";
export default {
name:"Dialog",
setup(){
let isShow = ref(false);
return {isShow};
}
}
</script>
<style scoped>
.mask{
background:rgba(0, 0, 0, .6);
position: absolute;
top:0;bottom:0;right:0;left:0;
}
.dialog{
width: 300px;
height: 100px;
padding: 10px;
background: lightgoldenrodyellow;
border-radius: 5px;
position:absolute;
top:10%;
left:50%;
transform: translateX(-50%);
}
.header{
padding-bottom: 2px;
border-bottom:1px solid gray;
display: flex;
justify-content: space-between;
}
.content{
padding-top: 5px;
}
</style>
- 启动应用,测试效果
来做个小实验,感受下“传送门”哈。
关于teleport,Vue3官网如是说(还没有实践用过,仅学习用):
Teleport 提供了一种干净的方法,允许我们控制在 DOM 中哪个父节点下渲染了 HTML,而不必求助于全局状态或将其拆分为两个组件。