search

Home  >  Q&A  >  body text

Rewrite the title to: Vue 3: Transfer content to element and replace

I'm using Vue 3's teleport to render an element into a div and it works as expected.

Teleport will add the item to the selected element but will not replace the current element in the div.

How do I set up the teleport to replace elements within the div, similar to how a vue application replaces the content of an anchor div when mounted?

Background: For SEO reasons, I need placeholder elements until the app renders and delivers.

<!-- 应用程序外部的HTML -->
<div>
  <div id="teleport-here">传送占位符...我希望这个被传送组件替换</div>
  <div id="app">当应用程序挂载时,这个占位符将被应用程序替换...</div>
</div>

<!-- 传送组件 -->
<teleport to="#telport-here">
  <div>传送内容...</div>
</teleport>


P粉237029457P粉237029457459 days ago1028

reply all(1)I'll reply

  • P粉903969231

    P粉9039692312023-11-07 09:40:07

    You need to have some separate logic to remove placeholders when necessary.

    Set the content of the placeholder to empty 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>

    reply
    0
  • Cancelreply