当前位置:   article > 正文

vue3快速入门-Teleport(瞬移组件)_vue瞬间组件

vue瞬间组件

查看本系列文章合集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>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
<script lang="ts">
import { defineComponent } from "vue";
import ModalButton from "../components/ModalButton.vue";

export default defineComponent({
  components: {
    ModalButton,
  },
  setup() {
    return {};
  },
});
</script>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

子组件-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>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
<script lang="ts">
import { defineComponent, ref } from "vue";

export default defineComponent({
  setup() {
    const modalOpen = ref(false);

    return { modalOpen };
  },
});
</script>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
<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>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24

to属性为body

在这里插入图片描述

to属性为#d1

在这里插入图片描述

:::

本文内容由网友自发贡献,转载请注明出处:https://www.wpsshop.cn/w/爱喝兽奶帝天荒/article/detail/746910
推荐阅读
相关标签
  

闽ICP备14008679号