Vue3TeleportforVue2

在 Vue 3 中,可以像这样将组件传送到body标签:

<template>
  <button @click="modalOpen = true">
    Open full screen modal! (With teleport!)
  </button>
    
  <teleport to="body">
    <div v-if="modalOpen">
      <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

用法 :

主文件

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


以上是Vue3TeleportforVue2的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>