最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Vue 3 Teleport for Vue 2 - Stack Overflow

programmeradmin4浏览0评论

In Vue 3 it's possible to Teleport a component to the body tag like so:

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

This causes the modal dialogue above to be rendered in the body tag. How can I achieve a similar thing in Vue 2?

In Vue 3 it's possible to Teleport a component to the body tag like so:

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

This causes the modal dialogue above to be rendered in the body tag. How can I achieve a similar thing in Vue 2?

Share Improve this question asked Feb 10, 2021 at 11:39 Muhammad Rehan SaeedMuhammad Rehan Saeed 38.4k47 gold badges216 silver badges327 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 20

Because Vue 2 doesn't support teleports, I recommend to use portal-vue component made for vue 2 :

Installation :

npm i portal-vue --save

Usage :

main.js

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

inside some child component :

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

in other place :

<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
发布评论

评论列表(0)

  1. 暂无评论