Incorporate custom JavaScript files that contain classes within a Vue component

i am encountering an issue with a js file that contains classes with functions. i have a vue component and i want to create an instance of that class within it. (when directly copying the file into my <script> tag, everything works smoothly)

myfile.js

class myclass{
  
  constructor(x){
      this.x=x
    }
}

within the script tag of the vue component, i am attempting to utilize

<script>
..
mounted(){
    let myinstance = new myclass("hi") 
    console.log(myinstance.x) 

}
..
</script>

-- at this point, i will mention what I've attempted (without success) so far, feel free to skip if you prefer a solution --

<script>
import myclass from "myfile.js"

this approach failed indicating that the js file needs to be installed first.

i made an attempt to install it, but encountered errors requesting a package.json file.

i created a package.json in the same directory as myfile.js

{
  "name"        : "myfile",
  "version"     : "0.0.1",
  "main"        : "myfile.js",
  "scripts"     : {
  },
  "dependencies": {
  }
}

however, i received an error stating Could not install from "....\src\baujs\myfile.js" as it does not contain a package.json file.

i have tried various methods without success, seems like i may be looking in the wrong direction. any guidance would be greatly appreciated. thank you in advance

Answer №1

To learn more about utilizing JS modules, please visit this page

In order to successfully utilize modules, start by exporting your class in a separate file named myFile.js:

export class myclass{
  
  constructor(x){
      this.x=x
    }
}

Next, import the class into your project:

import { myclass } from "myfile.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

Is it possible to transfer a value when navigating to the next component using this.props.history.push("/next Component")?

Is there a way I can pass the Task_id to the ShowRecommendation.js component? recommend = Task_id => { this.props.history.push("/ShowRecommendation"); }; Any suggestions on how to achieve this? ...

Clear session data when logging out from a dropdown list

I have a header that appears on several of my web pages. It contains a dropdown menu that allows users to log out by selecting the "Logout" option. When a user clicks on "Logout", I want to destroy the session variables associated with their session. Is t ...

Tips for maintaining blank lines while formatting .vue documents in VScode

I'm beginning to feel frustrated with the .vue framework because all of the VScode formatters I've tested are deleting empty lines. Everything else works smoothly, except for the fact that empty lines keep getting removed. All the effort I put ...

Troubleshooting: jQuery ajax form is not functioning as expected

After attempting various methods to create a basic jQuery Ajax form, I am puzzled as to why it is not submitting or displaying any notifications. Below is the code I have been working with: Javascript ... <script type="text/javascript" src="assets/js ...

Experience the innovative feature of React Splide Carousel where a peek of the next image is shown until you reach

My current challenge arises when I reach the last slide in the slider. I am trying to prevent it from looping and instead stop with no extra space or any other images peeking out. To address this, I have utilized the padding: '5%' option, which ...

I'm curious about the correct method for updating a parent component using a shared service within the ngOnInit function in Angular version 13

There have been instances where I encountered a scenario multiple times, where I utilize a shared service within the ngOnInit of a component to update a value in another component, specifically its parent. This often leads to the well-known Error: NG0100: ...

Managing errors and error codes in React/Redux applications

I am currently exploring the most effective approach for managing errors, particularly when deciding between error codes and an errors object in response from my API. As I dive into building a multi-part form using react, each time a user progresses to th ...

Selecting radio button does not update corresponding label

I am having an issue with setting a radio button as checked. In the example snippet, it works perfectly fine but on my localhost, it is not working. Even though the input gets checked, the label does not change. Surprisingly, if I set another radio button ...

Executable program contained within npm bundle

I am working on creating an npm package that can be executed as a command from the shell. I have a package.json { "name": "myapp", "version": "0.0.6", "dependencies": { "async": "", "watch": "", "node-promise": "", "rmdir": "", " ...

Unable to install NPM on my Ubuntu system

Attempting to set up npm on Ubuntu, I initially confirm that NPM is not currently installed: jmlopez@desarrollo:/usr/share$ npm -v Command 'npm' not found, but can be installed with: sudo apt install npm However, upon trying to install it, I enc ...

jquery mouse event does not register on touch-based devices

I have a mouse move event set up to scroll a div. However, when I try to access the functionality using a tab it does not work. How can I integrate this functionality onto a touch device? $(document).ready(function(){ $('#tim').on('mous ...

Although AJAX $.post functions properly in the View, it seems to encounter issues when relocated to a separate .js file. Interestingly, all other JQuery functions work

I have recently delved into MVC, JQuery, and AJAX, and encountered a perplexing issue. After completing the initial development of a practice website, I dedicated time to enhance the interactivity using JQuery. Everything was functioning smoothly until I ...

Matching an element that contains a specific string in JS/CSS

I'm currently faced with an HTML file that's being generated by an outdated system, making it tricky for me to control the code generation process. The structure of the HTML code is as follows: <table cellpadding=10> <tr> ...

Guide on Generating SAS Token for Azure Table Storage in a jQuery Application

I am currently working on a jQuery web application that requires read-only access to an Azure Table Storage, fetching one record at a time by passing in the PartitionKey and RowKey. To simplify my code, I have integrated the Azure Storage JavaScript Client ...

Issues with ng-repeat causing the Angular Editable table to malfunction

<table class="table table-bordered"> <tbody> <tr ng-repeat="playerOrTeam in template.editableTable track by $index"> <td style="text-align: center;" ng-repeat="playerOrTeamCat in playerOrTeam track by $index"> ...

Is it considered poor practice for two components to both utilize the same module within the Vuex store?

Imagine you've created a brand new Vue component called BComponent, along with a fresh store module named BModule. Now, you find yourself in the situation where you need to utilize some state logic that's already been implemented in AModule for u ...

What could be the issue with this C# GridView code snippet?

I am facing an issue with a GridView that contains checkboxes. When I try to select a checkbox, I need to retrieve the values from that specific row. The problem lies in the fact that the chk variable in my C# code never evaluates to "true," preventing the ...

Tips for showing both label and value on a pie slice in Apex charts

I am currently utilizing apex chart within an angular application to showcase charts. I am specifically focusing on a pie chart and aiming to customize it by displaying labels on the values within each slice of the pie, similar to what is shown in the atta ...

Capturing a part of the screen using JavaScript for screen recording

I'm exploring the possibility of implementing a JavaScript screen recorder that captures a video feed rather than the entire screen. I'm wondering if it's achievable using getDisplayMedia or if there's a specific library for this purpos ...

Issue: Following the execution of babel build, the system is unable to locate the SCSS

I'm encountering issues when trying to deploy a react library to npm, specifically with errors related to scss files in my local builds. Despite using babel for transpilation to es5, the final files still have dependencies on scss files. For example, ...