Vue3中的Teleport(传送门)

290 阅读1分钟

动画片多啦A梦相信大家很多都看过,而且近几年又出现了相关的电影,作为小编一个男生来说,一直是对里面的静香念念不忘,有点跑偏了哈,今天小编介绍的Teleport就和多啦A梦的任意门一样,可以穿梭到任何的DOM中的任何地方模态框一直是实际开发中用到比较多的功能之一,在没有各种各样的组件之前,我们需要通过css中的定位对元素进行修饰,有了Teleport,我们就可以这样实现一个简单的模态的组件。大家还可以关注我的微信公众号,蜗牛全栈。

<style>  
    .area{      
        position: absolute;      
        left: 50%;      
        top:50%;      
        transform: translate(-50%,-50%);
        width: 200px;      
        height: 300px;      
        background:green;  
    }  
    .mask{      
        position: absolute;      
        left:0;      
        right:0;      
        top:0;     
        bottom:0;      
        background: #000;      
        opacity: 0.5; 
    }
</style>
<script>  
const app = Vue.createApp({      
    data(){          
        return {              
            show:false          
        }      
    },      
    methods:{          
        handleBtnClick(){              
            this.show = !this.show          
        }      
    },      
    template: `<div class="area">
                <button @click="handleBtnClick">按钮</button>              
                <teleport to="body">                  
                    <div class="mask" v-show="show"></div>              
                </teleport>              
            </div>`  
        })
  const vm = app.mount("#root")</script>

上面的例子是将元素传递到body中,如果要将元素传递到指定的DOM节点,我们要怎么处理呢?

我们通过Teleport中的to属性,可以将代码写成这样

<body>  
    <div id="root"></div>  
    <div id="hello"></div>
</body>
<script>  
const app = Vue.createApp({        
    data(){          
        return {              
            show:false          
        }      
    },      
    methods:{          
        handleBtnClick(){              
            this.show = !this.show         
        }      
    },      
    template: `<div class="area"> 
                <button @click="handleBtnClick">按钮</button> 
                // 类似css选择器,根据DOM元素不同,通过to属性设置传送的位置        
                <teleport to="#hello">          
                    <div class="mask" v-show="show"></div>        
                </teleport>      
            </div>` 
        })
  const vm = app.mount("#root")</script>