Vue 3 Teleport for Vue 2

问题描述

在 Vue 3 中,可以像这样将组件 Teleport 加入 body 标签

<template>
  <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>
</template>

<script>
export default {
  data() {
    return { 
      modalOpen: false
    }
  }
};
</script>

这会导致上面的模态对话在 body 标签中呈现。如何在 Vue 2 中实现类似的功能

解决方法

由于 Vue 2 不支持传送,我建议使用为 vue 2 制作的 portal-vue 组件:

安装:

npm i portal-vue --save

用法:

main.js

import Vue from "vue"
import PortalVue from 'portal-vue'
Vue.use(PortalVue)
...

在一些子组件中:

<portal to="destination">
  <p>This slot content will be rendered wherever the <portal-target> with name 'destination'
    is  located.</p>
</portal>

在其他地方:

<portal-target name="destination">
  <!--
  This component can be located anywhere in your App.
  The slot content of the above portal component will be rendered here.
  -->
</portal-target

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...