Save a customized JavaScript file and integrate it into a Vue component

As a newcomer to Vue.js, I have a question regarding calling functions from a custom JavaScript file within a Vue component. Here is what I attempted:

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>

After running npm run build, I encountered the following error message:

https://i.sstatic.net/F8OWJ.png

If anyone could provide assistance with this issue, I would greatly appreciate it.

Answer №1

1: When defining methods in a class, the function keyword is not required.

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

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

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

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

Answer №2

When working with APIs in Vue, it's important to remember that the API should not be treated as a Vue component and should not be included inside the components branch. If the API consists of utility functions, you have the option to either export them individually or as part of a single object.

// util.js - exporting individual functions
export function testCall (call) {};
export function testUser (user) {};

// Importing functions in a Vue app
import { testCall, testUser } from 'util.js';


// util.js - exporting functions as an object
function testCall (call)
{
}

function testUser (user)
{
}

export default
{
  testCall,
  testUser
}

// Importing API object in a Vue app
import API from 'util.js';

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Looking to screen usernames that allow for the use of the DOT (.), underscore (_), and Dash (-)?

I am using jQuery to filter usernames that are exactly 3 characters long. The validation criteria includes only allowing the following special characters: ., _, and - var filter = /^[a-zA-Z0-9]+$/; Therefore: if (filter.test(currentval)) { //valid ...

Enhancing the Efficiency of Android Programming

For my application, I am currently displaying 12 markers on a map, each of which triggers a dialog box showing the location's address when tapped. However, I believe there is a more efficient way to handle this. I have been experimenting with creating ...

Is there a way to view the full Heroku log file?

I am facing an issue with my build in Heroku and I need to access the full log as indicated in the build: npm ERR! A complete log of this run can be found in: npm ERR! /app/.npm/_logs/****logname*****-debug.log Can anyone guide me on how to retrieve t ...

Establishing a connection to an active process within Winappdriver with the utilization of JavaScript

As someone who is fairly new to working with JS and WinAppDriver, I am currently facing a challenge with testing a Windows-based "Click Once" application built on .Net. To launch this application, I have to navigate to a website through Internet Explorer a ...

The exit code 1 was triggered in the npm-lifecycleindex.js file at line 285,

0 silly lifecycle <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="bac9ced5c8d194c9cadbfa8b948a948a">[email protected]</a>~build.prod: Args: [ '/d /s /c', 10 silly lifecycle 'gulp build.prod --color --en ...

Exploring how to read class decorator files in a Node.js environment

I've developed a custom class decorator that extracts permissions for an Angular component. decorator.ts function extractPermissions(obj: { [key: 'read' | 'write' | 'update' | 'delete']: string }[]) { re ...

Struggling to fill in fields using express and Mongodb

I am facing an issue with populating the fields of two models, Post and User. const PostSchema = new Schema({ text: { type: String }, author: { type: mongoose.Schema.Types.ObjectId, ref: 'user' } }) cons ...

Try utilizing the 'id name ends with' parameter within the on() function for creating dynamic bindings

I need help with dynamically binding the change event to multiple select input fields that are generated within my form. The item field is generated with IDs like: id="id_form-0-item" id="id_form-1-item" id="id_form-2-item" ... Although I have attempte ...

Mobile website scroll assistant

Seeking a solution to aid mobile users in scrolling through a lengthy article page. Typically in mobile apps, an alphabetical index assists users in navigating long lists. How can I incorporate a similar feature into a webapp? For context, my tech stack i ...

Using React and graphql to show information on selected options across components

Currently, I'm facing a challenge in determining my next step. In productList.js, there is a straightforward select dropdown class component that displays all data from Products (id, name, brand,vintage) using graphql(apollo). It successfully sho ...

The v-menu closes before the v-list-item onclick event is detected

I have set up the following menu using vue and vuetify: <div id="app"> <v-app id="inspire"> <div class="text-center"> <v-menu> <template v-slot:activator="{ on }"> ...

I have written code in JavaScript, but now I am interested in converting it to jQuery

What is the best way to convert this to jQuery? showDish("balkandish1") function showDish(dishName) { var i; $(".city").css('display', 'none'); $("#" + dishName).css('display', 'block'); } ...

Are there any other options besides using the React Material-UI makeStyles() function for styling class Components?

While experimenting with the makeStyles() function in Material-UI's React library, I encountered a specific error message: The use of hooks is limited to the body of a function component. Below is a snippet of the code that triggered this error: ...

Issue with Selenium webdriver's element.click() method not operating as anticipated in Chrome while using Mocha framework

While testing the log in feature of a website, I encountered an issue where the .click() method did not perform as expected despite being able to locate the Login button. Here is the relevant JavaScript test code: driver.sleep(1000) driver.findElement(By ...

I prefer to avoid generating the document structure while parsing with JSOUP

Utilizing the Jsoup API to parse a section of HTML using the Jsoup.parse() method. However, during parsing, it includes the document structure in the HTML content. For Instance: <p><a href="some link">some link data</a> Some paragraph c ...

A handy feature of HTML5 is the dataset attribute, which

Is there a way to restrict the height of the dataset dropdown list in HTML? When using <input list="datalist"> with numerous elements, some might not be visible. Is it possible to limit the size of the list and enable vertical scrolling to display al ...

Error in docker build due to missing package.json file for a local npm dependency, but the application runs successfully using npm start

I am currently developing an npm module locally, which is a dependency in a client application. The directory structure looks like this: /app /client /src App.js package.json Dockerfile.dev /shared /contexts package.json ...

No data retrieved from POST API test

I am currently troubleshooting an issue with my API where it is returning 'undefined' when I try to POST something. Despite the object being present, the test is failing to pass Test Result: expect(received).toEqual(expected) // deep equality ...

What is the best way to choose a key from a discriminated union type?

I have a discriminated union with different types type MyDUnion = { type: "anonymous"; name: string } | { type: "google"; idToken: string }; I am trying to directly access the 'name' key from the discriminator union, like thi ...

Configuring cloud code on Back4App to automatically trigger a POST API request to update the ESP

I am a beginner when it comes to developing APIs and cloud code, and I need help figuring out how to create an API that can add or update users in my back4app database table to my sendinblue (ESP) contact list. Could someone provide guidance on what shoul ...