You can get an element to render anywhere in the DOM with the teleport
component in Vue 3:
<template><div><div><div><teleport to="body"><footer>This is the very last element on the page</footer></teleport></div></div></div></template>
This will render the footer
at the very end of the document body
:
<html><head><!-- ... --></head><body><div><div><div><!-- Footer element was moved from here... --></div></div></div><!-- ...and placed here --><footer>This is the very last element on the page</footer></body></html>
This is very useful when the logic and state are in one place, but they should be rendered in a different location.
One typical example is a notification (sometimes called a toast).
We want to be able to display notifications from wherever inside of our app. But the notifications should be placed at the end of the DOM so they can appear on top of the page:
<!-- DogList.vue --><template><div><DogCardv-if="dogs.length > 0"v-for="dog in dogs":key="dog.id"v-bind="dog"/><teleport to="#toasts"><!-- Show an error notification if we have an error --><Toastv-if="error"message="Ah shoot! We couldn't load all the doggos"></teleport></div></template>
Which will render this to the DOM:
<html><head><!-- ... --></head><body><div id="#app"><!-- Where our Vue app is normally mounted --></div><div id="toasts"><!-- All the notifications are rendered here,which makes positioning them much easier --></div></body></html>
Here's the complete documentation: https://vuejs.org/api/built-in-components.html#teleport