将自定义javascript文件导出到Vue组件
我是Vue.js的初学者,所以这个问题可能是重复的或幼稚的。我想调用Vue组件中自定义javascript文件中定义的函数。我做了这样的事 custom.js将自定义javascript文件导出到Vue组件,javascript,npm,vue.js,Javascript,Npm,Vue.js,我是Vue.js的初学者,所以这个问题可能是重复的或幼稚的。我想调用Vue组件中自定义javascript文件中定义的函数。我做了这样的事 custom.js class API{ function testCall(){ alert("test ok"); } } export {API} App.vue <template> <div id="app"> <img src="./assets/logo.png"&g
class API{
function testCall(){
alert("test ok");
}
}
export {API}
App.vue
<template>
<div id="app">
<img src="./assets/logo.png">
<HelloWorld msg="Welcome to Your Vue.js App"/>
<testcomponent :on-click="getData">
</testcomponent>
</div>
</template>
<script>
import HelloWorld from './components/HelloWorld.vue';
import TestComponent from './components/TestComponent.vue';
import API from './js/custom.js';
export default {
name: 'app',
components: {
HelloWorld,
TestComponent,
API
},
methods: {
getData(){
const apiObj = new API();
apiObj.testCall();
}
}
}
</script>
从“./components/HelloWorld.vue”导入HelloWorld;
从“./components/TestComponent.vue”导入TestComponent;
从“/js/custom.js”导入API;
导出默认值{
名称:“应用程序”,
组成部分:{
HelloWorld,
测试组件,
美国石油学会
},
方法:{
getData(){
const apiObj=新API();
apiObj.testCall();
}
}
}
当我使用npm运行build
进行构建时,我得到以下错误信息
有什么帮助吗?1:在一个类中定义您不需要的函数关键字
class API{
testCall(){
alert("test ok");
}
}
2:由于您正在使用export{API}
进行命名导出,因此您的导入语句应该是
import {API} from './js/custom.js';
3:
组件
选项用于在本地注册vue组件。由于API
不是vue组件,请将其从components
选项中删除。API不是vue组件-不应将其包含在components
分支中。此外,如果这只是一组实用程序函数,您可以逐个导出它们,也可以将它们作为包含对象导出
// util.js - individual functions
export function testCall (call) {};
export function testUser (user) {};
// Vue app
import { testCall, testUser } from 'util.js';
// util.js - object group
function testCall (call)
{
}
function testUser (user)
{
}
export default
{
testCall,
testUser
}
// Vue app
import API from 'util.js';
还有一点需要澄清——我的一些函数使用axios进行AJAX调用。如何访问custom.js中的-axios、jQuery等外部库?@SouvikGhosh使用
import
语句导入这些模块。例如,要使用axios,请使用从“axios”导入axios
导入axios,我尝试在我的custom.js文件和App.vue文件中导入它,但它们都不起作用,我遇到构建错误。也尝试过使用require(“axios”),但没用。没关系。它起作用了。我刚从npm安装了axios。谢谢