Photo by Dima Pechurin on Unsplash

An Introduction to Vue Teleport — A New Feature in Vue3

One of the new features of Vue3 that has been talked about for a while is the idea of Portals — or ways to move template HTML to different parts of the DOM. Portals, which are a common feature in React, were available in Vue2 under the portal-vue library.

  • A basic example of Teleport
  • Some cool code interactions

Purpose of the Teleport

The first thing we have to understand is when/why this Teleport function can come in handy.

How Vue Teleport works

Let’s say that we have some child component where we want to trigger a notification to pop up. As we were just discussing, it’s simpler if we render this notification in an entirely separate DOM tree than Vue’s root #app element.

<body>
<div id="app"></div>
<div id='portal-target'></div>
</body>
<template>
<div class='portals'>
<button @click='showNotification'> Trigger Notification! </button>
<teleport to='#portal-target'>
<div class='notification'>
This is rendering outside of this child component!
</div>
</teleport>
</div>
</template>

<script>
import { ref } from 'vue'
export default {
setup () {
const isOpen = ref(false)

var closePopup

const showNotification = () => {
isOpen.value = true

clearTimeout(closePopup)

closePopup = setTimeout(() => {
isOpen.value = false
}, 2000)
}

return {
isOpen,
showNotification
}
}
}
</script>

<style scoped>
.notification {
font-family: myriad-pro, sans-serif;
position: fixed;
bottom: 20px;
left: 20px;
width: 300px;
padding: 30px;
background-color: #fff;
}
</style>
  • class of an element
  • data selector
  • a responsive query string

Conclusion

And that’s a quick introduction to Vue Teleport. I’ll likely write an in-depth guide to some more advanced use cases in the near future, but this should be a great place to get started working with this cool feature!

teaching web dev at https://learnvue.co | sharing my content creation tips at https://mattmaribojoc.com

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store