简体   繁体   中英

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. I want to create backward-compatible components which will get a full HTML module through an ajax request and insert it inside the component.

The problem is the excepted HTML contains relevant scripts that should be included. is there any option to inject js files from the server through HTML code

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

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 :

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);
          }
        })
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM