Vue introduction of remote file JS

problem

Recently in use Vue to do something, to use the scan function nail login here need to introduce remote js file, because not the same with the previous Vue way, do not want to download the file to a local application, to find a way to solve it , seemingly requires the introduction of third-party libraries, and finally found a solution, share it.

Thinking

The idea from the beginning was finished loading after Vue Dom ( mounted), use of JavaScript into the remote script file in the body.

Vue later found the  createElement method, a simple package components to solve the problem.

Solution

First version of the code (operation directly Dom) as follows:

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);
  },
}

Use  createElement method:

Export default { 
  Components: {
     'dingtalk' : { 
      the render (the createElement) { 
        return the createElement (
           'Script' , 
          { 
            attrs: { 
              type: 'text / JavaScript' , 
              the src: 'https://g.alicdn.com/dingding/ dinglogin / 0.0.2 / ddLogin.js' , 
            }, 
          }, 
        ); 
      }, 
    }, 
  }, 
} 
 
// use <dingtalk> </ dingtalk> call page

The ultimate program

By encapsulating a component  remote-js to achieve:

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

Instructions:

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

Since the beginning of learning Vue have any questions welcome to point out that we can discuss the discussion.

Reference material

Guess you like

Origin www.cnblogs.com/wpcnblog/p/10974156.html