How does Vue introduce remote JS files? How does vue introduce js files?
Problem
Recently, we have been using Vue to do things and use the dingtalk login scan function. We need to introduce remote js files because the Vue method is different from the previous one, I didn't want to download the file to a local application. I found a solution. It seems that all of them need to introduce a third-party library. Finally, I found a solution and shared it.
Ideas
The idea at the beginning is that after the Vue loads the Dom (mounted
), Use JavaScript scripts to insert remote script files into the body.
Later, we foundcreateElement
A component is encapsulated to solve the problem.
Solution
The first code (directly operating Dom) is 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 the createElement method:
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', },},},},}, // use <dingtalk> </dingtalk> to call it on the page
Ultimate Solution
Encapsulate a componentremote-js
Implementation:
export default { components: { 'remote-js': { render(createElement) { return createElement('script', { attrs: { type: 'text/javascript', src: this.src }}); }, props: { src: { type: String, required: true }, }, }, },}
Usage:
<remote-js src="https://g.alicdn.com/dingding/dinglogin/0.0.2/ddLogin.js"></remote-js>
If you have any questions about learning Vue at the beginning, please point out that we hope it will be helpful to your learning and support the help house.