vue 项目中引入外部 js 文件以及 HTML 文件
最近在项目中遇到了一个需求,就是要在vue项目中引用后台指定的HTML页面和一些外部的js文件,并在vue项目中使用,下面就记录一下吧。1、引入外部 js 文件在util.js文件中封装一个工具函数,专门用来引入外部 js 文件,使用时只需传入外部 js 文件的地址即可,该函数会返回创建好的script标签。export function createScript(src) {const s =
·
最近在项目中遇到了一个需求,就是要在vue项目中引用后台指定的HTML页面和一些外部的js文件,并在vue项目中使用,下面就记录一下吧。
1、引入外部 js 文件
在util.js
文件中封装一个工具函数,专门用来引入外部 js 文件,使用时只需传入外部 js 文件的地址即可,该函数会返回创建好的script
标签。
export function createScript(src) {
const s = document.createElement("script");
s.type = "text/javascript";
s.src = src;
const scriptElement = document.body.appendChild(s);
return scriptElement;
}
在组件中使用:
<script>
import { createScript } from "@/utils/util";
export default {
mounted() {
// 引入外部js文件
const scriptElement = createScript(
"http://xxx.com.xxx.js"
);
scriptElement.onload = function () {
// 输出xxx.js中的xxx
console.log(window.xxx);
};
},
};
</script>
2、引入外部 HTML 文件
要引入外部 HTML,首先服务器能返回我们一个 html 文件,我们通过发送网络请求,得到服务器返回我们的 html 文件,然后通过vue
中的v-html
指令,将其内容渲染为 html 标签,展示给用户。
<template>
<div>
<h1>工作区</h1>
<div v-html="html"></div>
</div>
</template>
<script>
export default {
data() {
return {
html: "",
};
},
created() {
this.load();
},
methods: {
// 加载远程html
load() {
axios.get('http://www.xxx.com', {
headers: {
accept: "text/html;charset=UTF-8"
},
params: {},
}).then((res) => {
console.log(res);
this.html = res.data
})
.catch((err) => {
console.log(err);
});
},
}
}
</script>
更多推荐
已为社区贡献1条内容
所有评论(0)