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:

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

What is the method for displaying data from a JSON file that is associated with the wallet address of the authenticated user in next.js?

I am currently working on a claim page using next.js, where logged in Metamask addresses can perform the following tasks: Access data from a local .json file to check eligibility for claiming an item and display the claim page. Submitting a form to update ...

Vue - Error Message from Eslint Regarding Absence of Variable in Setup Function

Interestingly, the Vue.js documentation strongly recommends using the <script setup> syntax of the Composition API. The issue with this recommendation is that the documentation lacks depth and it conflicts with other tools (like eslint). Here is an e ...

Is there a way to incorporate a component into Particle.js?

I attempted to encase the Particle around the component but it's not functioning correctly import React from "react"; import { render } from "react-dom"; import Particles from "./Particles"; import "./index.css" ...

I am having trouble with the `electron` package as `require("electron").app` is showing as undefined. I have just installed new npm

Just yesterday, I was working flawlessly on Electron. But today, when I tried to work on it again, I encountered a major issue where Electron was not functioning at all. To troubleshoot, I deleted the node_modules folder and performed a fresh npm install. ...

Tips for Incorporating the YouTube Iframe API into Your ReactJS Project

While working in React, I am attempting to build a custom YouTube player component that includes a new set of player controls. The YouTube iframe API provides the following code snippet for creating a player instance: var tag = document.createElement(&ap ...

Exploring the process of web scraping from dynamic websites using C#

I am attempting to extract data from using HtmlAgilityPack. The website is dynamic in nature, displaying content after the page has fully loaded. Currently, my code retrieves the HTML of the loading bar using this method, but encounters a TargetInvocation ...

Making multiple Node.js requests using the request module: A comprehensive guide

Purpose: My goal is to extract data from approximately 10,000 web pages using Node.js. Issue: The scraping process speeds through the first 500~1000 pages but then significantly slows down beyond that point, sometimes halting completely. To initiate the ...

Is it possible to share an .ics file using SparkPost in a Node.js environment?

Attempting to generate an i-cal event and link it to a sparkpost transmission in the following manner: const event = cal.createEvent({ start: req.body.a.start, end: req.body.a.end, summary: req.body.a.title, description: req.body.a.body, ...

Angular and Express: Automatically redirecting to the previous page after user login

A question similar in nature can be found here, although not directly relevant to my situation. Within my Single Page Application, I am implementing PassportJS for user authentication. There are multiple routes that necessitate user login. The routing is ...

Reactive map not triggering Vue computed() function

Having a reactive relationship with an initially empty map: const map = reactive({});, I also have a computed property that checks if the map contains a key named "key": const mapContainsKeyComputed = computed(() => map.hasOwnProperty("key")). However, ...

Stop the selection of text within rt tags (furigana)

I love incorporating ruby annotation to include furigana above Japanese characters: <ruby><rb>漢</rb><rt>かん</rt></ruby><ruby><rb>字</rb><rt>じ</rt></ruby> However, when attemp ...

Arrays in Javascript (correlating)

I'm having trouble figuring out what needs to be included in this code (I apologize that it's in German, it's an array corresponding to images for JavaScript.) function namenZuBildern(){ var bilder = new Array( "000227", "000228", " ...

What is the process for applying a border to the chosen image within the ImageList of the MaterialUI component?

Currently, I have set up the images in a grid format using the and components from MaterialUI. However, I am looking to implement an additional feature where when a user clicks on a specific image from the grid, a border is displayed around that select ...

Ways to obtain every image placed onto an element

Using the img tag within div.image-block sets a background. Images can be added to .block3 through drag and drop. Is there a way to create a container that includes all elements from .image-block? <style> .image-block { position: relat ...

Difficulty loading AngularJS 1.3 page on Internet Explorer 8

Being an avid user of Angular, it pains me to even bring up the topic of IE8, a browser that many consider to be pure evil and deserving of extinction. Despite my reservations, I am experiencing difficulties with loading Angular 1.3 in IE8. The page break ...

In search of a JavaScript library that can help format strings to meet the requirements of JSON formatting

Utilizing jQuery ajax, I am transmitting updates from the client's browser to my server. However, I have noticed that there are certain characters not supported by JSON that require an additional "\" in front of each one to be properly sent. The ...

Error: Unable to access undefined properties (reading 'url')

I am currently working on creating a drag-and-drop card game and I have encountered an issue with the react-dnd library. When using data from the file, everything works fine, but if I have to fetch the data externally, it throws an error. This problem see ...

How to invoke a function from a different ng-app in AngularJS

I have 2 ng-app block on the same page. One is for listing items and the other one is for inserting them. I am trying to call the listing function after I finish inserting, but so far I haven't been successful in doing so. I have researched how to cal ...

Running npm commands from the root directory while the package.json file is located elsewhere

Although I understand that it's not ideal, I am faced with a specific directory structure that cannot be changed: [projectRootDir] [src] [tests] [otherDirs] [configuration] package.json mocha.opts other files.. ...

I am attempting to adjust the color of the active tab, but I seem to be encountering issues in my code. Can anyone help me

The currently active tab should change along with the text inside the box, but it's not working as expected. I'm struggling to find out why. Here is a fiddle to demonstrate my progress so far: var btn1 = document.getElementById("btn1"); va ...