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

相关推荐
持敬chijing2 小时前
Web渗透之前后端漏洞-文件上传漏洞-过滤绕过与配置文件漏洞-条件竞争漏洞
前端·安全·web安全·网络安全·网络攻击模型·安全威胁分析
尼斯湖皮皮怪2 小时前
iceCoder:验收门控深度分析
前端·agent
周庆猛2 小时前
Babylon.js 多灯场景在 Windows 上报错:VERTEX shader uniform block count exceeds GL_MAX_VE
前端·数据可视化
胡志辉2 小时前
深入浅出理解浏览器事件循环:从一道输出题讲到 Chrome 源码
前端·javascript·面试
槑有老呆2 小时前
用 Bun 写一个 RESTful TodoList,顺便把面向接口编程整明白
前端
英勇无比的消炎药2 小时前
别再盲目混用AI组件库和传统组件库差距原来这么大
前端·vue.js
ViavaCos2 小时前
AI 帮我写代码,我帮 AI 踩坑:Vue 大数据表格优化全记录
前端·性能优化
lichenyang4533 小时前
聊天消息的「状态」该怎么存?从一堆 boolean 到一个状态机
前端
gz-郭小敏3 小时前
优化横向滚动展示大量数据的时候数据晃动问题
前端·javascript·html·css3
ClouGence3 小时前
自动化测试 CueCast 新版本发布:录制更稳、回放更准、排障更清晰
前端·程序员·测试