【问题标题】:Vue v-html directive does not run <script src=".."> tagsVue v-html 指令不运行 <script src=".."> 标签
【发布时间】:2021-06-05 18:34:46
【问题描述】:

我正在尝试创建一个需要支持系统旧模块的 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;
        })
  }
};

【问题讨论】:

    标签: html ajax vue.js vue-component script


    【解决方案1】:

    您将无法为此使用v-html,因为该指令只是设置元素的innerHTML,它不会执行&lt;script&gt; 标签。

    AFAIK,唯一的其他选择是在文档中附加一个 &lt;script&gt; 与预期的源,所以也许你可以创建一个 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);
              }
            })
    }
    

    【讨论】:

      猜你喜欢
      • 2015-06-07
      • 2019-05-06
      • 2013-06-27
      • 1970-01-01
      • 2012-08-24
      • 1970-01-01
      • 2021-10-23
      • 2019-08-25
      • 2021-10-19
      相关资源
      最近更新 更多