Teleport/index.vue
<script>
export default {
name: 'teleport',
props: {
/* 移动至哪个标签内,最好使用id */
to: {
type: String,
required: true
}
},
mounted() {
// 把内容移动到指定的标签内this.to渲染
document.querySelector(this.to).appendChild(this.$el)
},
beforeDestroy() {
// 移除内容
const targetElement = document.querySelector(this.to)
if (targetElement && targetElement.contains(this.$el)) {
targetElement.removeChild(this.$el)
}
},
render() {
return this.$scopedSlots.default()
}
}
</script>
使用示例:
<Teleport to="body"> </Teleport>