查看本系列文章合集click me
下载本系列文章源码click me
Teleport
是一种能够将我们的模板移动到 DOM 中 Vue app 之外的其他位置的技术。
如果我们嵌套在 Vue app 内的某个组件内部,那么处理嵌套组件的定位、z-index 和样式就会变得很困难。
使用 Teleport
就可以方便的解决组件间 css 层级问题
我们将模态内容包装在 teleport 组件中,还需要指定一个 to
属性,为该属性分配一个查询选择器,以标识目标元素。
父组件
<template>
<div id="d1">
<h3>第一个div</h3>
</div>
<div id="d2">
<h3>第二个div</h3>
</div>
<ModalButton></ModalButton>
</template>
<script lang="ts">
import { defineComponent } from "vue";
import ModalButton from "../components/ModalButton.vue";
export default defineComponent({
components: {
ModalButton,
},
setup() {
return {};
},
});
</script>
子组件-teleport
<template>
<div>
<button @click="modalOpen = true">弹出一个模态框</button>
<teleport to="body">
<div v-if="modalOpen" class="modal">
<div>
这是一个弹框,挂载在 body 元素上。
<button @click="modalOpen = false">关闭</button>
</div>
</div>
</teleport>
</div>
</template>
<script lang="ts">
import { defineComponent, ref } from "vue";
export default defineComponent({
setup() {
const modalOpen = ref(false);
return { modalOpen };
},
});
</script>
<style scoped>
.modal {
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
background-color: rgba(0, 0, 0, 0.5);
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
}
.modal div {
display: flex;
flex-direction: column;
align-items: center;
justify-content: space-around;
background-color: white;
width: 350px;
height: 300px;
padding: 5px;
}
</style>
to属性为body
to属性为#d1
:::