目前项目有个需求就是,在vue页面中引入额外的config.js。常规引入有以下几种方法:
1.main.js直接引用
2.index.html中标签引用
3.import引入
以上不符合我们业务需求,所以整理了第四种方式:通过组件,定义为script标签引入外部js
4.1-这个写法不太便于理解,我没有使用
// 使用 vue 的 createElement 创建script 组件 嵌入到body中
components: {
scriptLink: {
render(createElement) {
return createElement('script', {
attrs: {
type: 'text/javascript',
src: '//g.alicdn.com/sd/smartCaptcha/0.0.1/index.js',
},
});
},
},
}
4.2-我使用的方法
//封装一个remote-js组件
components: {
'remote-js': {
render(createElement) {
return createElement('script', {
attrs: {
type: 'text/javascript',
src: `${require('baseUrl')}/config.js`,
},
});
},
props: {
//src可以直接定义在标签上,向上面所示,也可以定义在props中,在标签使用时传入。
// src: { type: String, required: true },
},
},
},
使用:
能看到已经被加载:
image.png
给个点击事件输出一下看看
getConfig() {
console.log(testUrl);
},
完美
image.png