前言:
在項目中,我們會遇到這樣的情況,我們在一個組件中,想實現一個彈框(模態框),但是這個彈框我們想全屏,這樣的話,需要把彈框的父元素設置為body, 這個怎么實現呢?
vue3 實現方法:
<button @click="modalOpen = true">
Open full screen modal! (With teleport!)
</button>
<teleport to="body">
<div v-if="modalOpen" class="modal">
<div>
I'm a teleported modal!
(My parent is "body")
<button @click="modalOpen = false">
Close
</button>
</div>
</div>
</teleport>
vue2的變通實現方法如下:
父元素中
<Pop ref="pop" v-if="show" /> script中邏輯大概如下: jump() { this.show = true; this.$nextTick(() => { this.$refs.pop.renderHtml(); }); }
子元素中:
script中:
methods: {
renderHtml(param = true) {
const body = document.querySelector('body');
if (param) {
this.$nextTick(() => {
if (body.append) {
body.append(this.$el);
} else {
body.appendChild(this.$el);
}
});
} else {
body.removeChild(this.$el);
}
}
}
<template> <div class="pop-box" ref="popBox"> <div class="content"> <span> {{ popContent.title }} </span> <span> {{ popContent.content }} </span> <div @click="renderHtml(false)">{{ popContent.confirm }}</div> </div> </div> </template>
這里子元素可以自己關閉自己。
以上便是vue3和vue2實現將dom轉移到某個元素底下的方法,可以理解為乾坤大挪移!
