Create portals to render content in another part of the DOM, instead of inside the Vue component
January 02, 2019 🕒 1 minute, 1 second
Portal and Portal 2 were two of the most addictively creative games ever. The original Portal game was released in 2007 and Portal 2 followed in 2011. I still remember being glued to the screen and spending hours solving some of the more challenging puzzles.
But before I get too nostalgic let me focus on the subject matter for a bit. 😃
Portals provide a way to render content into a DOM node that exists outside the hierarchy of the Vue component. The concept of portals also exists in React. When the need arises I rely on the portal-vue library to create portals, which provides a really clean syntax:
<div id="app"> <portal to="destination"> <p>Content.</p> </portal> <portal-target name="destination"></portal-target> </div>
While it's not strictly elegant it's possible to render content outside of the Vue app by referencing the destination by id:
<div id="app"> <portal target-el="#destination"> <p>Content.</p> </portal> </div> <div id="destination"></div>
The upcoming Vue 3 will add framework support for fragments and portals, which is fantastic news.