简体   繁体   中英

Vue 3 teleport to element and replace content

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>

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM