vue3 Teleport 的vue2实现方法(改变组件父元素为body或者其他元素)

前言:

在项目中,我们会遇到这样的情况,我们在一个组件中,想实现一个弹框(模态框),但是这个弹框我们想全屏,这样的话,需要把弹框的父元素设置为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转移到某个元素底下的方法,可以理解为乾坤大挪移!

posted @ 2022-04-02 10:46  茶记忆  阅读(1070)  评论(0编辑  收藏  举报