Eliahu Garcia Lozano

Eliahu Garcia Lozano

How to Teleport in Vue 3

How to Teleport in Vue 3

Subscribe to my newsletter and never miss my upcoming articles

A few days ago I decided it was time for me to update myself to the new version of Vuejs, Vue 3. And today I wanted to share with you the first thing I learn that version two didn't have, the teleport component.

It's well known that modern web applications fit in a div.

Ok, React uses #root and Vue uses #app but they just do the same, which is inject the JavaScript code into that div. So here it comes the question:

What if I have an element I want to display as a sibling of the #app element in the html?

Sometimes we have a loader or a modal (aka popup) component that is not part of the app, but anyway, it will be injected inside the #app element. Thus, the html will look like this:

<html>
  <body>
    <div id="app">
      <!-- Other injected HTML here -->
      <div class="loader">
        <!-- HTML for the loader goes here -->
      </div>
    </div>
  </body>
</html>

Let's teleport!

Goku Teleport

To use the teleport component in your app, you need to first, add a sibling to the #app element in the html.

<html>
  <body>
    <div id="app"></div>
      <!-- built files will be auto injected -->
    <div class="loader"></div>
      <!-- loader component will be injected here -->
  </body>
</html>

Once you've done that, go to your .vue file and use the teleport component:

<template>
  <teleport to=".loader" v-if="showLoader">
    <Loader />
  </teleport>
  <!-- The logic of your component goes below -->
</template>

And that's it. Now, when the showLoader condition is met, the loader will show in the specified html element. Notice that I used a CSS selector so if the element was an id, I could have done it like this: <teleport to="#loader" v-if="showLoader">

If you found it useful, please like, subscribe, and share the knowledge.

You might like what I share on my Twitter too.

 
Share this