当前位置: 移动技术网 > IT编程>开发语言>JavaScript > vue组件内部引入外部js文件的方法

vue组件内部引入外部js文件的方法

2020年03月09日  | 移动技术网IT编程  | 我要评论

之所以要做这个是因为,在一个组件内部需要引入一个js文件来定位。如果放在,这样每个组件都会有这个js。所以需要在组件内单独引入。

第一种操作 dom引入js:

export default {
 mounted() {
  const s = document.createelement('script');
  s.type = 'text/javascript';
  s.src = '你的需要的js文件地址';
  document.body.appendchild(s);
 },
}

第二种使用 createelement 方法:

export default {
 components: {
  'remote-js': {
   render(createelement) {
    return createelement(
     'script',
     {
      attrs: {
       type: 'text/javascript',
       src: '你的需要的js文件地址',
      },
     },
    );
   },
  },
 },
}
// 使用 <remote-js></remote-js> 在页面中调用

第三种封装一个组件:

importjs.js

// 导入外部js
import vue from 'vue'
 
vue.component('remote-script', {
  render: function (createelement) {
    var self = this;
    return createelement('script', {
      attrs: {
        type: 'text/javascript',
        src: this.src
      },
      on: {
        load: function (event) {
          self.$emit('load', event);
        },
        error: function (event) {
          self.$emit('error', event);
        },
        readystatechange: function (event) {
          if (this.readystate == 'complete') {
            self.$emit('load', event);
          }
        }
      }
    });
  },
  props: {
    src: {
      type: string,
      required: true
    }
  }
});
// 引入
import 'common/importjs.js'
// 使用
<remote-script src="https://pv.sohu.com/cityjson?ie=utf-8"></remote-script>

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网