简体   繁体   English

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

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

I'm trying to create a Vue SPA app which needs to support old modules of the system.我正在尝试创建一个需要支持系统旧模块的 Vue SPA 应用程序。 I want to create backward-compatible components which will get a full HTML module through an ajax request and insert it inside the component.我想创建向后兼容的组件,它将通过 ajax 请求获取完整的 HTML 模块并将其插入到组件中。

The problem is the excepted HTML contains relevant scripts that should be included.问题是排除的 HTML 包含应该包含的相关脚本。 is there any option to inject js files from the server through HTML code是否有任何选项可以通过 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;
        })
  }
};

You won't be able to use v-html for this because the directive simply sets an element's innerHTML , which does not execute <script> tags.您将无法为此使用v-html ,因为该指令只是设置元素的innerHTML ,它不执行<script>标签。

AFAIK, the only other option is to append to the document a <script> with the intended source, so perhaps you could create an API to fetch the scripts separate from the markup, then inject them into the document : 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