Teleport 可以将我们模板有些与模板有关联的逻辑代码(只是逻辑有关)移动到DOM 中 Vue app 之外的其他位置,
比如,模态框组件,模态框的逻辑存在于组件中,但是模态框的快速定位就很难通过 CSS 来解决,或者需要更改组件组合。
使用Teleport将模态框的一部分代码移动
// 父组件
<template>
<div>
父组件
<child />
</div>
</template>
<script>
import { defineComponent } from "vue";
import child from "./teleportChild.vue";
export default defineComponent({
name: "",
components: {
child,
},
});
</script>
<style scoped></style>
// 子组件 child
<template>
<div>
<button @click="isShow = true">点击我显示弹出框</button>
<teleport to="body">
<div v-show="isShow">
我是弹出框
<button @click="isShow = false">点我关闭弹出框</button>
</div>
</teleport>
</div>
</template>
<script>
import { ref } from "vue";
export default {
name: "teleportChild",
setup() {
const isShow = ref(false);
return { isShow };
},
};
</script>
<style scoped></style>
与 Vue components 一起使用
如果 包含 Vue 组件,则它仍将是 父组件的逻辑子组件:
const app = Vue.createApp({
template: `
<h1>Root instance</h1>
<parent-component />
`
})
app.component('parent-component', {
template: `
<h2>This is a parent component</h2>
<teleport to="#endofbody">
<child-component name="John" />
</teleport>
`
})
app.component('child-component', {
props: ['name'],
template: `
<div>Hello, {{ name }}</div>
`
})
在这种情况下,即使在不同的地方渲染 child-component,它仍将是 parent-component 的子级,并将从中接收 name prop。
这也意味着来自父组件的注入按预期工作,并且子组件将嵌套在 Vue Devtools 中的父组件之下,而不是放在实际内容移动到的位置
在同一目标上使用多个 teleport
<teleport to="#modals">
<div>A</div>
</teleport>
<teleport to="#modals">
<div>B</div>
</teleport>
<!-- 最终结果-->
<div id="modals">
<div>A</div>
<div>B</div>
</div>
多个 组件可以将其内容挂载到同一个目标元素。顺序将是一个简单的追加——稍后挂载将位于目标元素中较早的挂载之后。