Teleport
是一种能够将我们的模板移动到 DOM 中 Vue app 之外的内置组件
teleport 里的to 指向渲染组件的dom
在哪里显示就通过注册id使用,to和id必须一样
使用场景
例:比如可以注册一个全局的提示信息,这里我封装了一个子组件,子组件里写teleport内置组件,在app.vue里注册id,teleport页面调用子组件。
子组件
<template>
<div class='portals'>
<button @click='submit'> 提交 </button>
<teleport to='#portal-target'>
<div v-if="flag" class='notification'>
提交成功
</div>
</teleport>
</div>
</template>
<script setup>
import {ref} from 'vue'
const flag = ref(false)
const submit = () => {
flag.value = true
setTimeout(() => {
flag.value = false
}, 2000)
}
</script>
<style scoped>
.notification {
font-family: myriad-pro, sans-serif;
position: fixed;
bottom: 20px;
left: 20px;
width: 300px;
padding: 30px;
background-color: #fff;
}
</style>
teleport页面
<template>
<div>
<Page/>
</div>
</template>
<script setup>
import Page from '../components/Page.vue'
</script>
<style scoped>
</style>
app.vue页面
<template>
<nav>
<router-link to="/">Home</router-link> |
<router-link to="/about">About</router-link> |
<router-link to="/teleport">teleport</router-link>
<div id="portal-target"></div>
</nav>
<router-view/>
</template>
<style lang="scss">
#app {
font-family: Avenir, Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
}
nav {
padding: 30px;
a {
font-weight: bold;
color: #2c3e50;
&.router-link-exact-active {
color: #42b983;
}
}
}
</style>
效果图