繁体   English   中英

将自定义javascript文件导出到Vue组件

[英]Export custom javascript file to a Vue component

我是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">
    <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>

当我使用npm run build ,出现以下错误。

在此处输入图片说明

请帮忙吗?

1:要在类中定义方法 ,则不需要function关键字。

class API{
    testCall(){
        alert("test ok");
    }
}

2:由于您正在使用export {API}进行命名导出,因此您的import语句应为

import {API} from './js/custom.js';

3: components选项用于在本地注册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';

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM