Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
February 2, 2021 03:34 am GMT

How to Teleport in Vue 3

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>
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

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.


Original Link: https://dev.to/eligarlo/how-to-teleport-in-vue-3-1a9e

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To