1

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?

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

4 Comments

One more clarification- some of my functions are using axios for AJAX calls. How do I get access to the external libraries like- axios, jQuery in the custom.js?
@SouvikGhosh import those modules using import statement. For e.g. to use axios import it using import axios from 'axios'
I tried importing it in my custom.js file and also App.vue file but none of them worked and I got build error. Also tried using require("axios") but did not work.
Never mind. It works. I just had to install axios from npm. Thanks!!
2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.