Vue references external JS and calls methods in JS files
Several methods of introducing JS files into VUE projects
When developing a Vue project, sometimes it is necessary to use some js libraries in non-ES6 format without export, which can be achieved in the following ways:
1. Use the script tag to introduce in the index.html page
Of course, you can also use the address of CDN. The content introduced in this way is global and can be used everywhere.
<!DOCTYPE html>
<html lang=zh-CN>
<head>
<meta charset=utf-8>
<meta http-equiv=X-UA-Compatible content="IE=edge">
<meta name=viewport
content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no,viewport-fit=cover">
<title>网签合同查询</title>
<link rel=stylesheet href=./static/index.b0707a6a.css>
**被引入的JS**
<script src=https://isdapp.shandong.gov.cn/jmopen/jssdk/index.js charset=utf-8></script>
</head>
<body>
<div id=app></div>
<script src=./static/js/chunk-vendors.9051d855.js></script>
<script src=./static/js/index.d88e62c6.js></script>
</body>
</html>
2. Use window.moduleName in main.js to use
It can also be put into Vue.prototype so that it can be used in components.
var THREE = window.THREEvar GLTFLoader = THREE.GLTFLoader
Vue.prototype.THREE = THREE
3. Manually add export
Put export default {/method to be exported /} for the method that needs to be used in the js library, and then use it through import {*} from
In the JS library:
function realconsole(){
alert("hello world!"); }
export {
realconsole }
In the component that needs to use the JS library:
import realconsole from './xxx'
4. Use the import method to mount the methods in the required js library to the global
import '@static/libs/GLTFLoader'
// 可以从全局获取导入的方法
let GLTFLoader = THREE.GLTFLoader
Out of the box: If we need to call the method of the vue page in the method of the called JS file, we can do the following
Call the method in vue in js
Register the method to the window object on the vue page, and then directly call window.xxx on the js page
demo. vue
mounted() {
window.functionForJs = this.functionForJs
},
methods: {
functionForJs(data) {
console.log('接收参数', data)
}
}
demo.js
export function doSomething() {
window.functionForJs('哈哈哈')
}