Vue移动 HTML 元素到指定位置 teleport 标签

teleport 标签:用于将组件中的 HTML 元素移动到任意的位置。

使用 teleport 标签移动 HTML 元素:

html 复制代码
<!-- 将 teleport 中的内容移动到 body 标签中  -->
<teleport to="body">
    <div>
        <h3>我是第三层组件的标题</h3>
        <p>我是第三层组件的内容</p>
        <p>我是第三层组件的内容</p>
        <p>我是第三层组件的内容</p>
    </div>
</teleport>

注:teleport 标签也可以通过 id 名移动,例如:`<teleport to="#box">`

使用 teleport 标签制作全局弹窗:

第一层组件:

html 复制代码
<template>
  <div class="one">
    <h3>我是One组件(第一层)</h3>
    <hr />
    <Two></Two>
  </div>
</template>

<script>
import Two from '../components/Two';
export default {
  name: "One",
  components: { Two }
}
</script>

第二层组件:

html 复制代码
<template>
    <div class="two">
        <h3>我是Two组件(第二层)</h3>
        <hr />
        <Three></Three>
    </div>
</template>

<script>
import Three from "../components/Three.vue"
export default {
    name: "Two",
    components: { Three }
}
</script>

第三层组件(弹窗组件):使用 teleport 标签将弹窗内容移动到 body 标签中。

javascript 复制代码
<template>
    <button @click="isShow = true">显示弹窗</button>
    <teleport to="body">
        <div class="mask" v-if="isShow">
            <div class="dialog">
                <h3>我是弹窗的标题</h3>
                <p>我是弹窗的内容</p>
                <p>我是弹窗的内容</p>
                <p>我是弹窗的内容</p>
                <button @click="isShow = false">关闭弹窗</button>
            </div>
        </div>
    </teleport>
</template>

<script>
import { ref } from 'vue'
export default {
    name: "Three",
    setup() {
        let isShow = ref(false);
        return { isShow }
    }
}
</script>

<style scoped>
.mask {
    width: 100vw;
    height: 100vh;
    background-color: rgba(0, 0, 0, 0.5);
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    z-index: 999;
    display: flex;
    justify-content: center;
    align-items: center;
}

.dialog {
    width: 300px;
    padding: 20px;
    background-color: aqua;
    text-align: center;
}
</style>

最终效果:

原创作者:吴小糖

创作时间:2023.11.21

相关推荐
Lee川6 小时前
从零解剖一个 AI Agent Tool是如何实现的
前端·人工智能·后端
wangruofeng7 小时前
Playwright 深度调研:为什么它成了浏览器自动化的新底座
前端·测试
李白的天不白9 小时前
SSR服务端渲染
前端
卷帘依旧10 小时前
SSE(Server-Sent Events)完全指南
前端
码云之上10 小时前
万星入坞:我们如何用三层插件体系干掉巨石应用
前端·架构·前端框架
kyriewen10 小时前
一口气讲清楚 Monorepo、Turborepo、pnpm、Changesets 到底是什么?
前端·架构·前端工程化
IT_陈寒11 小时前
React性能优化踩的坑,这个错你可能也会犯
前端·人工智能·后端
zhangxingchao11 小时前
AI应用开发三:RAG技术与应用
前端·人工智能·后端
摘星小杨11 小时前
如何在前端循环调取接口,实时查询数据
开发语言·前端·javascript
Hilaku11 小时前
从搜索排名到 AI 回答? 先聊一聊 AI 可见度工具 BuildSOM !
前端·javascript·程序员