Rewrite the title to: Vue 3: Transfer content to element and replace
P粉237029457
P粉237029457 2023-11-06 11:01:38
0
1
983

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粉237029457
P粉237029457

reply all(1)
P粉903969231

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>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template