loading

Vue Teleport

To relocate content inside the DOM structure, use the Vue <Teleport> tag.

< Teleport > and The 'to' Attribute

Using the ‘to’ attribute to specify the destination and the Vue <Teleport> tag surrounding the content, we can transport content to a different location within the DOM structure.

				
					<Teleport to="body">
  <p>Hello!</p>
</Teleport>
				
			

Since the value of the ‘to’ attribute is provided in CSS notation, all we need to do to transfer material to the body tag, like in the code above, is write <Teleport to=”body”>.

Examining the page after it has loaded allows us to see that the material has been relocated to the body tag.

Example

CompOne.vue:

				
					<template>
  <div>
    <h2>Component</h2>
    <p>This is the inside of the component.</p>
    <Teleport to="body">
      <div id="redDiv">Hello!</div>
    </Teleport>
  </div>
</template>
				
			

The red <div> element has been relocated out of the component and to the end of the <body> tag, as can be seen if we right-click on our page and select ‘Inspect’.

Vue Teleport -

Another option would be to use <Teleport to=”#receivingDiv”> around the content we wish to relocate or teleport, and then have a tag with the id <div id=”receivingDiv”>.

Script and Style of Teleported Elements

Relevant functionality contained within the component’s <script> and <style> tags continues to function for the transferred content, even when some content has been moved out of the component via the <Teleport> tag.

Example

Even after compilation, the teleported <div> element is no longer inside the component, yet relevant code from the <style> and <script> tags still functions for it.

CompOne.vue:

				
					<template>
  <div>
    <h2>Component</h2>
    <p>This is the inside of the component.</p>
    <Teleport to="body">
      <div 
        id="redDiv" 
        @click="toggleVal = !toggleVal" 
        :style="{ backgroundColor: bgColor }"
      >
        Hello!<br>
        Click me!
      </div>
    </Teleport>
  </div>
</template>

<script>
export default {
  data() {
    return {
      toggleVal: true
    }
  },
  computed: {
    bgColor() {
      if (this.toggleVal) {
        return 'lightpink'
      }
      else {
        return 'lightgreen'
      }
    }
  }
}
</script>

<style scoped>
#redDiv {
  margin: 10px;
  padding: 10px;
  display: inline-block;
}

#redDiv:hover {
  cursor: pointer;
}
</style>
				
			
Share this Doc

Vue Teleport

Or copy link

Explore Topic