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?
1 Answer
Reset to default 20Because 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