VUE项目中引入JS文件的几种方法

在开发Vue项目的时候,有时需要使用一些非ES6格式的没有export的js库,可以有如下方法实现:

1.在index.html页面使用script标签引入

当然也可以使用cdn的地址。这样引入后的内容是全局的,可以在所有地方使用。

<!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.在main.js中使用window.moduleName 使用

也可以放入Vue.prototype中,这样组件内都可以使用。

var THREE = window.THREEvar GLTFLoader = THREE.GLTFLoader

Vue.prototype.THREE = THREE

3.手动添加export

为js库中需要使用的方法放入export default { /要导出的方法/},然后通过import {*} from 使用

在JS库中:

function realconsole(){  

    alert("hello world!");  }  

 export {  

     realconsole }

在需要使用JS库的组件中:

import realconsole from './xxx'

4. 使用import方式,把需要的js库中的方法挂载到全局

import '@static/libs/GLTFLoader'

// 可以从全局获取导入的方法 

let GLTFLoader = THREE.GLTFLoader

话外:若我们需要在被调用的JS文件的方法中去调用vue页面的方法可以进行以下操作

js中调用vue中的方法

在 vue 页面将方法注册到 window 对象上, 之后在js页面直接 window.xxx 调用即可

demo.vue

mounted() {
    window.functionForJs = this.functionForJs 
},
methods: {
    functionForJs(data) {
        console.log('接收参数', data)
    }
}

demo.js

export function doSomething() {
    window.functionForJs('哈哈哈')
}

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐