首页 > 解决方案 > Vue 3 传送到元素并替换内容

问题描述

我正在使用vue 3 传送来渲染 div 中的元素,它按预期工作。

Teleport 会将项目添加到所选元素,但不会替换 div 中的当前元素。

如何设置瞬移以替换 div 中的元素,类似于 vue 应用程序在安装时替换锚 div 内容的方式?

上下文:出于 SEO 原因,我需要占位符元素,直到应用程序呈现和传送。

<!-- 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>

标签: javascripthtmlvue.js

解决方案


您需要有一些单独的逻辑来在必要时删除占位符。

将占位符的内容设置为空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>


推荐阅读