Create portals to render content in another part of the DOM, instead of inside the Vue component

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. 

Not surprisingly The Daily Beast was referring to Portal 2 as The Best Videogame Ever (with a question mark at the end though) and people were writing love letters praising the game back in the day.

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>

When necessary it's possible to render content outside of the Vue app by referencing the destination by id:

<div id="app">
  <portal name="" target-el="#destination">
    <p>Content.</p>
  </portal>
</div>
  
<div id="destination"></portal-target>

The upcoming Vue 3 will add framework support for fragments and portals, which is fantastic news.

Did you like this post?
Previous post

Let's take a hypothetical JSON object that holds various pieces of data and describes a request for currency conversion. Then let's explore how JSON Schema can help with the validation of its structure.

Next post

This post collects a few notes on how to mock asynchronous API calls when testing Vue components.