簡體   English   中英

html 內容呈現在 Iframe 但不在 div

[英]html content renders in Iframe but not in div

我想創建一個渲染另一個 vue 應用程序的 Vue 應用程序。 這是通過創建一個 Express 文件服務器來實現的,該服務器為要呈現的應用程序的 index.html 提供服務。

我創建了一個帶有 div 容器的文件,並從我的文件服務器獲取要呈現的應用程序。

<template>
  <div id="customAppContainer"></div>
</template>

<script>
export default {
  async mounted() {
    const fullRoute = this.$router.currentRoute.fullPath;
    const routeSegments = fullRoute.split("/");
    const appsIndex = routeSegments.indexOf("apps");
    const appKey = routeSegments[appsIndex + 1]; // The name of the app

    const response = await fetch(`http://localhost:3000/apps/${appKey}`); // fetch the index.html
    const html = await response.text(); // convert the filecontent to a string
    document.getElementById("customAppContainer").innerHTML = html; // load the file content into the div
  }
};
</script>

通過這樣做,我得到一個空白頁並且沒有控制台錯誤。 但是 DOM 顯示 html 字符串在該 div 容器中創建了有效的 DOM 元素。 When I change the div to an iframe and assign the fetch url as a src of that iframe this iframe is able to render the Vue app / index.html file correctly.

出於調試目的,這是我從文件服務器獲得的 HTML 字符串:

<!DOCTYPE html><html lang=en><head><meta charset=utf-8><meta http-equiv=X-UA-Compatible content="IE=edge"><meta name=viewport content="width=device-width,initial-scale=1"><link rel=icon href=/favicon.ico><title>my custom app</title><link href=/js/app.5eb51f47.js rel=preload as=script><link href=/js/chunk-vendors.c3422c1d.js rel=preload as=script></head><body><noscript><strong>We're sorry but my custom app doesn't work properly without JavaScript enabled. Please enable it to continue.</strong></noscript><div id=customApp></div><script src=/js/chunk-vendors.c3422c1d.js></script><script src=/js/app.5eb51f47.js></script></body></html>

如何避免 iframe 並將 html 內容加載到 div 中?

我終於通過將 object 嵌入到 div 容器中並將其數據分配給 src url 來使其工作。

<template>
  <div id="customAppContainer"></div>
</template>

<script>
export default {
  async mounted() {
    const fullRoute = this.$router.currentRoute.fullPath;
    const routeSegments = fullRoute.split("/");
    const appsIndex = routeSegments.indexOf("apps");
    const appKey = routeSegments[appsIndex + 1];

    document.getElementById(
      "customAppContainer"
    ).innerHTML = `<object data="http://localhost:3000/apps/${appKey}"></object>`;
  }
};
</script>

您是否嘗試過使用指令v-html 此處(針對 Vue 2)或此處(針對 Vue 3)查看 Vue 的文檔。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM