Teleport 可以将我们模板有些与模板有关联的逻辑代码(只是逻辑有关)移动到DOM 中 Vue app 之外的其他位置,(根据DOM 元素的id进行和Teleport的to属性对应)
比如,模态框组件,模态框的逻辑存在于组件中,但是模态框的快速定位就很难通过 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代码
//teleport属性值 to="body" 等于挂载到body DOM 上(目标元素)
<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>