Vue 3 teleport to element and replace content

Viewed 1860

I'm using vue 3 teleport to render elements in a div and it works as expected.

Teleport will add items to the selected element, but won't replace current elements in div.

How can I set teleport to replace the elements in div similar to how a vue app replaces anchor div content when mounted?

Context: I need placeholder elements for SEO reasons until app renders and teleports.

<!-- HTML outside the app -->
<div>
  <div id="teleport-here">Teleport placeholder... I want this to be replaced by the teleport component</div>
  <div id="app">This placeholder will be replaced with app when app mounts...</div>
</div>

<!-- teleport component -->
<teleport to="#telport-here">
  <div>Teleport content...</div>
</teleport>
1 Answers

You'd need to have some separate logic which removes the placeholder when necessary.

Set the placeholders' content to nothing in setup:

Vue.createApp({
  setup() {
    const placeholder = document.getElementById('teleport-here');

    placeholder.innerHTML = '';
  }
}).mount('#app');
<script src="https://unpkg.com/vue@next"></script>

<div>
  <div id="teleport-here">Teleport placeholder... I want this to be replaced by the teleport component</div>
  <div id="app">This placeholder will be replaced with app when app mounts...
    <!-- teleport component -->
    <teleport to="#teleport-here">
      <div>Teleport content...</div>
    </teleport>
  </div>
</div>

Related