簡體   English   中英

Vue v-html 指令不運行<script src=“..”> tags

[英]Vue v-html directive does not run <script src=“..”> tags

我正在嘗試創建一個需要支持系統舊模塊的 Vue SPA 應用程序。 我想創建向后兼容的組件,它將通過 ajax 請求獲取完整的 HTML 模塊並將其插入到組件中。

問題是排除的 HTML 包含應該包含的相關腳本。 是否有任何選項可以通過 HTML 代碼從服務器注入 js 文件

<template>
  <div class="container" v-html="html"></div>
</template>

<script>
import { mapState } from "vuex";

export default {
  name: "comp",
  data() {
    return {
      html: null
    };
  },
  mounted() {
        fetch('http://localhost:8090/api/html/response')
        .then(response => {
          return response.text();
        })
        .then(data => {
          this.html= data;
        })
  }
};

您將無法為此使用v-html ,因為該指令只是設置元素的innerHTML ,它不執行<script>標簽。

AFAIK,唯一的其他選擇是將帶有預期源的<script>附加到文檔,因此也許您可以創建一個 API 來獲取與標記分開的腳本,然后將它們注入到document

export default {
  mounted() {
    fetch('http://localhost:8090/api/js/response')
        .then(response => {
          return response.json();
        })
        .then(scriptUrls => {
          for (const url of scriptUrls) {
            const scriptEl = document.createElement('script');
            scriptEl.src = url;
            document.body.appendChild(scriptEl);
          }
        })
}

暫無
暫無

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

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