1. 程式人生 > 其它 >VUE3 之 Teleport - 這個系列的教程通俗易懂,適合新手

VUE3 之 Teleport - 這個系列的教程通俗易懂,適合新手

1. 概述

老話說的好:宰相肚裡能撐船,但凡成功的人,都有一種博大的胸懷。

言歸正傳,今天我們來聊聊 VUE 中 Teleport 的使用。

2. Teleport

2.1 遮罩效果的實現 

    <style>
       .area {
            position: absolute;
            left: 50%;
            top: 50%;
            transform: translate(-50%, -50%);
            width: 200px;
            height: 300px;
            background
: rgb(16, 209, 48); } .mask { position: absolute; left: 0; right: 0; top: 0; bottom: 0; background: #000; opacity: 50%; } </style>
<body>
    <div id="myDiv"></div>
</
body>
    const app = Vue.createApp({
       data() {
            return {
                show : false
            }
       },
       methods: {
            handleClick(){
                this.show = !this.show;
            }
       },
       template:`
           <div class="area">
               <button @click="handleClick">按鈕</button>
                <div class="mask" v-show="show"></div>
           </div>
       `
   });
   const vm = app.mount("#myDiv");

 這個例子,我們實現了一個簡單的遮罩效果,但這個遮罩效果並沒有遮罩整個背景,只是遮罩了 area 這個div。

2.2 Teleport 的使用

    const app = Vue.createApp({
       data() {
            return {
                show : false
            }
       },
       methods: {
            handleClick(){
                this.show = !this.show;
            }
       },
       template:`
           <div class="area">
               <button @click="handleClick">按鈕</button>
               <teleport to="body" >
                    <div class="mask" v-show="show"></div>
               </teleport>
           </div>
       `
   });

 這個例子中,我們改進了一下,使用 <teleport to="body" > 將遮罩的 div 轉移到了 body 元素下,因此遮罩範圍擴大到了整個 body 的區域。

2.3 Teleport 通過 元素id 轉移元素到指定元素下

<body>
    <div id="myDiv"></div>
    <div id="maskDiv"></div>
</body>
   const app = Vue.createApp({
       data() {
            return {
                show : false
            }
       },
       methods: {
            handleClick(){
                this.show = !this.show;
            }
       },
       template:`
           <div class="area">
               <button @click="handleClick">按鈕</button>
               <teleport to="#maskDiv" >
                    <div class="mask" v-show="show"></div>
               </teleport>
           </div>
       `
   });

這個例子中,通過 <teleport to="#maskDiv" > 的寫法,將 遮罩div 轉移到了 id 是 maskDiv 的元素下。 

3. 綜述

今天聊了一下 VUE 中 Teleport 的使用,希望可以對大家的工作有所幫助,下一節我們繼續講 Vue 中的高階語法,敬請期待

歡迎幫忙點贊、評論、轉發、加關注 :)

關注追風人聊Java,這裡乾貨滿滿,都是實戰類技術文章,通俗易懂,輕鬆上手。

4. 個人公眾號

追風人聊Java,歡迎大家關注