Vue3 Teleport移动元素位置
作者:温新
时间:2021-08-12
hi,我是温新,一名PHPer
Teleport用户更改元素的位置。一个常见的场景是创建一个包含全屏模式的组件。在大多数情况下,你希望模态框的逻辑存在于组件中,但是模态框的快速定位就很难通过 CSS 来解决,或者需要更改组件组合。
案例:将vue接管区域的某个元素修改到body元素下。
<style>
    .container {
        width:200px;
        height: 100px;
        background-color: aqua;
    }
    .modal {
        background-color: green;
    }
</style>
<body id="body">
    <div id="app">
        <div class="container">
            <button @click="clickMe">clike me</button>
            <!-- 将class为modal的div元素移动到 body 元素 -->
            <teleport to="body">
                <div class="modal" v-show="show"></div>
            </teleport>
        </div>
    </div>
</body>
<script>
    const app = Vue.createApp({
        data () {
            return {
                show:false
            }
        },
        methods:{
            clickMe(){
                this.show = !this.show;
            }
        }
    });
    const vm = app.mount('#app');
</script>
需要移动的元素需要使用teleport进行包裹,并指定要移动到哪个元素下。
我是温新
每天进步一点,就一点点
请登录后再评论