dan*_*iel 5 html ajax vue.js vue-component
我正在尝试创建一个 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;
})
}
};
Run Code Online (Sandbox Code Playgroud)
您将无法使用v-html此功能,因为该指令只是设置元素的innerHTML,而不会执行<script>标签。
AFAIK,唯一的其他选择是将预期源附加到文档 a 中<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);
}
})
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1699 次 |
| 最近记录: |