之所以要做这个是因为, 在一个组件内部需要引入一个 JS 文件来定位. 如果放在 index.html, 这样每个组件都会有这个 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>
image.PNG
来源: http://www.jianshu.com/p/5a3445b968d1