Vue component encounters issue with exporting JavaScript functions

I decided to streamline my code by moving some functions into a JavaScript file like this:

[...]
function changeToEditView(reportId)
{
    let pathEdit="/edit/"+reportId;
    this.$router.push({ path: pathEdit, replace: true });
}
[...]
export {convertDate, deleteReport, changeToEditView, getPdfByReportId}

However, when I import these functions into my Vue component like this

import axios from 'axios'
import convertDate from '@/js/methods' 
import deleteReport from '@/js/methods'
import changeToEditView from '@/js/methods'
import getPdfByReportId from '@/js/methods'
export default 
{
[...]
methods:
    {
        convertDate,
        deleteReport,
        changeToEditView,
        getPdfByReportId,

I encounter the following warning messages:

 warning  in ./src/views/DashboardView.vue?vue&type=script&lang=js

export 'default' (imported as 'deleteReport') was not found in '@/js/methods' (possible exports: changeToEditView, convertDate, deleteReport, getPdfByReportId)

 warning  in ./src/views/DashboardView.vue?vue&type=script&lang=js

export 'default' (imported as 'changeToEditView') was not found in '@/js/methods' (possible exports: changeToEditView, convertDate, deleteReport, getPdfByReportId)

 warning  in ./src/views/DashboardView.vue?vue&type=script&lang=js

export 'default' (imported as 'getPdfByReportId') was not found in '@/js/methods' (possible exports: changeToEditView, convertDate, deleteReport, getPdfByReportId)

I attempted adding 'default' after export in the JavaScript file like this but none of the functions seem to work

export default {convertDate, deleteReport, changeToEditView, getPdfByReportId}

Answer №1

There are a few issues that need to be addressed in your code.

Firstly, make sure to update your script so that it exports named functions. Here's an example:

export const changeToEditView = (reportId) => {
  let pathEdit="/edit/"+reportId;
  this.$router.push({ path: pathEdit, replace: true });
};

export const deleteReport = () => {
/*  */
};

Then, import these functions using the following syntax:

import { changeToEditView, deleteReport } from '@/src/path-to-file';

You can now use these methods within your Vue component without needing to register them or prepend with this..

For instance:

methods: {
  doStuff() {
    deleteReport();
    changeToEditView();
  },
},

This resource provides more information on the difference between named exports and default exports.

Another issue is that accessing this.$router directly may not work as expected. You should instead import your Vue router instance to utilize the .push method.

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

The CSS styling is not being rendered correctly on the AngularJS HTML page

Encountering a puzzling situation here. Our angular controller is successfully delivering data to the page, but we are facing an issue with rendering a table due to an unknown number of columns: <table border="1" ng-repeat="table in xc.tables"> ...

Prevent anchor link click and drag functionality on an HTML page / Swipe through a container containing links

Is there a way to prevent clicking and dragging on a link in a webpage? When you click the left mouse button on a link and drag it, you can unintentionally move the link or open a new tab. I am looking for a way to disable this behavior using JavaScript o ...

What are the steps to create a JSON file structured in a tree format?

Can you provide instructions on creating a JSON file in the following tree format? root child1 child11 child2 child21 child22 child3 child31 I am looking to generate a sample JSON file that adheres to the ...

Using Json with React's Context API

I am dealing with nested JSON and arrays within it. My goal is to create a Search functionality that will iterate through the arrays and, based on a specific ID, display the name of the corresponding object in the array. I attempted using the Context API ...

Utilizing the Google Maps API to geocode addresses and postponing the retrieval of the data

Utilizing Google's maps API to geocode two addresses has brought about a unique challenge for me. I am deferring the returned results and utilizing a $.when().then() method to execute my logic once I receive the coordinates for the string addresses. T ...

Showing a Vue component within a Laravel Blade template

Currently, I am performing a basic calculation within app.js by multiplying the product price with the quantity. My goal is to showcase the total value in Laravel for users to preview their order. app.js const app = new Vue({ el: '#item', ...

Displaying foreign exchange rates using Shield UI Chart

In my quest to access and display forex data, I have stumbled upon the incredible Shield UI Chart. After some experimentation, I successfully mastered the art of implementing ajax: $.ajax({ url: 'http://api.apirates.com/jsonp/update', dataTy ...

Using Vue to set an active class on an element and retrieve the current DOM element

I am attempting to apply a class called "active" to the currently selected element without using v-for. When the element is clicked, I assign event.target to the "selected" property. To compare each individual element with the one stored in "selected", I n ...

Having trouble inserting an image using Vue?

I am having trouble understanding why only the first image loads, while the others do not. 1. <img :src="require('../assets/batatas.jpg')" :alt="item.title" /> 2. <img :src="'../assets/batatas.jpg'" ...

What is the best way to incorporate messages across various channels with a Discord bot?

While browsing through the questions of other users, I stumbled upon exactly what I was looking for. My dilemma now is how to make the same bot perform similar tasks on various channels but with different titles, footers, and so on... The primary code sni ...

The dropdown value is limited to storing data up to the specified space

I am facing an issue with storing data selected from the second dropdown in my form. The first dropdown is for selecting the Brand Name of a car, and the second dropdown retrieves data from the database based on the brand name selected. I have used a div t ...

Is it necessary for me to set up @types/node? It appears that VSCode comes with it pre-installed

Many individuals have been adding @types/node to their development dependencies. Yet, if you were to open a blank folder in VSCode and create an empty JavaScript file, then input: const fs = require('fs'); // <= hover it and the type display ...

Limiting the usage of a command in Discord.js to one user at a time, rather than all users

I'm in the process of developing a discord.js bot and I need to implement a cooldown for a specific command. After searching several tutorials online, I found that most of them apply the cooldown to all commands (meaning all users have to wait a set ...

Sending data as a string in an AJAX request

I have been struggling with this coffeescript function that controls dynamic select boxes. I am trying to pass the content of "modelsSelect" to another script, but for some reason, it's not working as intended. customScript.coffee dynamicSelection = ...

How can the hreflang tag be used correctly in a React application that supports multiple languages?

I have a React application with 3 pages(routes) and I support 2 languages (English and Spanish). Should I insert the following code into the <head></head> section of the public\index.html file like this? <link rel="alternate" ...

The functionality of jquery.load() seems to be experiencing issues in Internet Explorer when attempting to load an HTML file

Code $('.form').load('http://'+window.location.hostname+':8423/html/form/form_generate.html/?session='+session); In an attempt to load a html file from a different port on the same server. The original server is accessible ...

Having difficulty incorporating custom JavaScript files into a testing framework

I am facing a unique challenge while integrating the Page Object design pattern into my test suite using selenium-webdriver and node.js. The first page object, pageObject/admin/login/index.js, works seamlessly. It contains selectors and methods to fill ou ...

The 'file' property of undefined throws an error in ng-file-upload

I am currently exploring the functionality of ng-file-upload from this repository: https://github.com/danialfarid/ng-file-upload I have successfully implemented the basic setup as follows: HTML: <section ng-controller="MyController"> ...

Encountered a Puppeteer Protocol issue: Error occurred when attempting to call a function on a closed

Exploring the world of JavaScript and nodejs as a beginner. Attempting to create a PDF table with node.js through Google puppeteer. Referenced a tutorial for the code below, all credit goes to the original source. Using a sample HTML template to populat ...

express has a req.body that is devoid of any content

When making a request to my local server in my React app, the code looks like this: fetch("http://localhost:4000/signup", { method: "POST", mode: "no-cors", body: JSON.stringify({ name: "Joe", lname: "Doe& ...