What is portal-vue?
portal-vue is a Vue.js plugin that allows you to render a component's template in a different part of the DOM tree. This can be particularly useful for creating modals, tooltips, and other UI elements that need to be rendered outside of their parent component's DOM hierarchy.
What are portal-vue's main functionalities?
Basic Portal
This feature allows you to move a piece of the template to another part of the DOM. The `portal` component is used to specify the content to be moved and the `to` attribute specifies the target element.
<template>
<div>
<portal to="destination">
<p>This content will be teleported to the destination element.</p>
</portal>
<div id="destination"></div>
</div>
</template>
<script>
import { Portal } from 'portal-vue';
export default {
components: {
Portal
}
};
</script>
Named Portals
Named portals allow you to manage multiple portals more easily by giving each portal a unique name.
<template>
<div>
<portal to="destination" name="example">
<p>This content will be teleported to the destination element with a specific name.</p>
</portal>
<div id="destination"></div>
</div>
</template>
<script>
import { Portal } from 'portal-vue';
export default {
components: {
Portal
}
};
</script>
Scoped Slots
Scoped slots allow you to pass data from the parent component to the teleported content, making it more dynamic and interactive.
<template>
<div>
<portal to="destination" v-slot="props">
<p>{{ props.message }}</p>
</portal>
<div id="destination"></div>
</div>
</template>
<script>
import { Portal } from 'portal-vue';
export default {
components: {
Portal
},
data() {
return {
message: 'This is a scoped slot message.'
};
}
};
</script>
Other packages similar to portal-vue
react-portal
react-portal is a React library that provides similar functionality to portal-vue for React applications. It allows you to render children into a DOM node that exists outside the DOM hierarchy of the parent component.
PortalVue
A Portal Component for Vue 3, to render DOM outside of a component, anywhere in the document.
For more detailed documentation and additional Information, please visit the docs.
Looking for the version for Vue 2.*? Docs for PortalVue 2.*, compatible with Vue 2, are here
Installation
npm i portal-vue
yarn add portal-vue
import PortalVue from 'portal-vue'
Vue.use(PortalVue)
Usage
<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">
</portal-target>
Nuxt module
Add portal-vue/nuxt
to modules section of nuxt.config.js
{
modules: ['portal-vue/nuxt']
}