vue3 teleport傳送門的使用

定義:可以將組件的DOM元素直接傳送到某一位置進行展示。
  • 使用場景:像 modals,toast 等這樣的元素,很多情況下,我們將它完全的和我們的 Vue 應用的 DOM 完全剝離,管理起來反而會方便容易很多
1、未使用teleport的時候
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>test</title>
    <style>
        .area {
            position: absolute;
            left: 50%;
            top: 50%;
            transform: translate(-50%, -50%);
            width: 200px;
            height: 200px;
            background: black;
        }
        
        .mask {
            position: absolute;
            left: 0;
            right: 0;
            top: 0;
            bottom: 0;
            background: green;
            opacity: 0.5;
        }
    </style>
    <script src="https://unpkg.com/vue@next"></script>
</head>

<body>
    <div id="root">
        <div class="area">
            <button @click="handleClick">按鈕</button>
            <div class="mask" v-show="show"></div>
        </div>
    </div>
</body>
<script>
    //自定義指令
    const app = Vue.createApp({
        data() {
            return {
                show: false
            }
        },

        methods: {
            handleClick() {
                this.show = !this.show
            }
        },

    });



    const vm = app.mount('#root');
</script>

</html>

效果:蒙層在div內部


2、使用teleport的時候
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>test</title>
    <style>
        .area {
            position: absolute;
            left: 50%;
            top: 50%;
            transform: translate(-50%, -50%);
            width: 200px;
            height: 200px;
            background: black;
        }
        
        .mask {
            position: absolute;
            left: 0;
            right: 0;
            top: 0;
            bottom: 0;
            background: green;
            opacity: 0.5;
        }
    </style>
    <script src="https://unpkg.com/vue@next"></script>
</head>

<body>

    <div id="root">
        <div class="area">
            <button @click="handleClick">按鈕</button>
            <teleport to='#mask'>
                <div class="mask" v-show="show"></div>
            </teleport>
        </div>
    </div>
    <div id="mask"></div>


</body>
<script>
    //自定義指令
    const app = Vue.createApp({
        data() {
            return {
                show: false
            }
        },

        methods: {
            handleClick() {
                this.show = !this.show
            }
        },

    });



    const vm = app.mount('#root');
</script>

</html>

效果:


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章