Vue3中Teleport的使用

一、Vue3.x传送

Vue3.x 中的组件模板应该属于组件,我们想把这个模板的内容移动到当前组件之外的 DOM 中,就可以使用 Teleport。

表示传送内包含的内容显示到身体中

<teleport to="body">
内容
</teleport>
<teleport to="#app">
内容
</teleport>

二、使用eleport实现一个模态T的组件

Modal.vue

<template>
<teleport to="body">
    <div class="model-bg" v-show="visible">
        <div class="modal-content">
            <button class="close" @click="$emit('close-model')">X</button>
            <div class="model-title">{{title}}</div>
            <div class="model-body">
                <slot>
                    第一个对话框
                </slot>
            </div>
        </div>
    </div>

</teleport>
</template>

<script>
export default {
    props: ["title", "visible"]
}
</script>

<style lang="scss">
.model-bg {
    background: #000;
    opacity: 0.7;
    width: 100%;
    height: 100%;
    position: absolute;
    top: 0px;
}

.modal-content {
    width: 600px;
    min-height: 300px;
    border: 1px solid #eee;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    background: #fff;

    .model-title {
        background: #eee;
        color: #000;
        height: 32px;
        line-height: 32px;
        text-align: center;
    }

    .model-body {
        padding: 40px;
    }

    .close {
        position: absolute;
        right: 10px;
        top: 5px;
        padding: 5px;
        border: none;
        cursor: pointer;
    }

}
</style>

Home.vue 使用模型

<template>
<div class="home">
    <button @click="isVisible=true">弹出一个模态对话框</button>
    <modal :visible="isVisible" title="用户登录" @close-model="isVisible=false"></modal>
</div>
</template>

<script>
import Modal from "./Modal"
export default {
    data() {
        return {
            isVisible: false
        }
    },
    components: {
        Modal
    }

}
</script>

<style lang="scss">
.home {
    position: relative;
}
</style>
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值