Souvik Ghosh
Souvik Ghosh

Reputation: 4606

Export custom javascript file to a Vue component

I am a beginner in Vue.js and so this question might be duplicate or naive. I want to call functions defined in a custom javascript file within a Vue component. I did something like this.

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>

When I build using npm run build, I get below error.

enter image description here

Any help with this please?

Upvotes: 1

Views: 7275

Answers (2)

IVO GELOV
IVO GELOV

Reputation: 14259

API is not a Vue component - you should not include it inside the components branch. Also, if this is just a bunch of utility functions you can either export them one by one or as a containing object

// 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';

Upvotes: 2

Vamsi Krishna
Vamsi Krishna

Reputation: 31362

1: To define methods in a class you do not need function keyword.

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

2: Since you are doing a named export using export {API}, your import statement should be

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

3:components options is for registering vue components locally. Since API is not a vue component remove it from the components option.

Upvotes: 2

Related Questions