'JavaScript export functions in vue component failed

I wanted to simplify my code, so i put some functions in a js file like that :

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

and when I import them in my vue component like that

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 have this message :

 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 tried to put 'default' after export in te js file like that but none of these functions work

export default {convertDate, deleteReport, changeToEditView, getPdfByReportId}


Solution 1:[1]

You've got several issues here.

The first is a simple one. Update your script to export named functions, for example:

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

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

And then import with:

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

You'll then be able to use these methods within your Vue component. You don't need to register them first, nor do you need to use this..

For example:

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

This answer explains the differences between named exports and default exports in a bit more detail.

The next issue, is that this.$router isn't going to be accessible like this. You will need to import your instance of Vue router to call .push on it.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1