How to Teleport in Vue 3

Web Developer | React.js | JavaScript | Check out my blog: https://blog.eligarlo.dev
Search for a command to run...

Web Developer | React.js | JavaScript | Check out my blog: https://blog.eligarlo.dev
No comments yet. Be the first to comment.
React is a popular JavaScript library that provides developers with a powerful and efficient way to build user interfaces. One of the key features of React is the ability to use a method called createPortal to render components outside the main conte...

For a good work-life balance, stay active and healthy.

Definition of trim, "To cut away unnecessary parts from something." - Oxford Dictionary. Sometimes, validating forms in JavaScript can be a tedious task for a developer. You have to check many things. For instance, that the values given are of the t...

We always have to validate if the arguments passed in a function have a value or they are undefined but, do we really? Introduction In my last post, I talked about Destructuring Assignment In A Function Parameter and why it is handy when you have opt...

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:
#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>

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.