5

在 Vue 3 中,可以像这样将组件传送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 中实现类似的功能?

4

1 回答 1

10

因为 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
于 2021-02-10T11:46:26.293 回答