首頁  >  問答  >  主體

將標題重寫為:Vue 3:將內容傳送到元素並進行替換

我正在使用Vue 3的teleport將元素渲染到一個div中,它按預期工作。

Teleport會將項目新增到所選元素中,但不會取代div中的目前元素。

我如何設定teleport以取代div中的元素,類似於vue應用程式在掛載時替換錨點div內容的方式?

背景:出於SEO的原因,我需要佔位元素,直到應用程式渲染和傳送。

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

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


#
P粉237029457P粉237029457347 天前942

全部回覆(1)我來回復

  • P粉903969231

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

    您需要有一些單獨的邏輯來在必要時刪除佔位符。

    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>

    回覆
    0
  • 取消回覆