Vue如何引入远程JS文件

直接在dom上操作:

export default {
 mounted() {
  const s = document.createElement('script');
  s.type = 'text/javascript';
  s.src = 'https://g.alicdn.com/dingding/dinglogin/0.0.2/ddLogin.js';
  document.body.appendChild(s);
 },
}

 

思路:

 用Vue 的 createElement 方法:

export default {
 components: {
  'dingtalk': {
   render(createElement) {
    return createElement(
     'script',
     {
      attrs: {
       type: 'text/javascript',
       src: 'https://g.alicdn.com/dingding/dinglogin/0.0.2/ddLogin.js',
      },
     },
    );
   },
  },
 },
}
 
// 使用 <dingtalk></dingtalk> 在页面中调用

 

终极方案:

通过封装一个组件 remote-js 实现:

export default {
 components: {
  'remote-js': {
  render(createElement) {
   return createElement('script', { attrs: { type: 'text/javascript', src: this.src }});
  },
  props: {
   src: { type: String, required: true },
  },
 },
 },
}

使用方法:

<remote-js src="https://g.alicdn.com/dingding/dinglogin/0.0.2/ddLogin.js">
</remote-js>

 

参考:

http://www.jb51.net/article/111634.htm

原文链接:http://blog.csdn.net/sinat_17775997/article/details/55798611

 

posted @ 2017-10-19 09:01  最爱小虾  阅读(27180)  评论(0编辑  收藏  举报