1
votes

I'm writing a Vue single page component in my project which is bundled using Laravel Mix. I want to extract some logic out into its own class so that it can be easily re-used across other components (but this isn't logic that should be a Vue component itself).

I made a new class and put it in TimeRangeConverter.js, in the same directory as my Vue component.

export default class TimeRangeConverter {
    static getFromTimestamp() {
        return 1;
    }
}

And in my component, I'm importing it as I think I normally would:

<template>
    <div>
        Example component
    </div>
</template>

<script>
    import './TimeRangeConverter';

    export default {
        mounted() {
            console.log(TimeRangeConverter.getToTimestamp());
        }
    }
</script>

However Vue is throwing an error saying ReferenceError: TimeRangeConverter is not defined.

I'm using the default webpack.mix.js config file that comes with Laravel 5.7:

mix.js('resources/js/app.js', 'public/js');

And in my main app.js file I'm automatically including Vue components with:

const files = require.context('./', true, /\.vue$/i);
files.keys().map(key => Vue.component(key.split('/').pop().split('.')[0], files(key).default));

What's the correct way to import this class into a Vue component for usage?

1

1 Answers

0
votes

You should import your class inside your component code using the following syntax :

 import TimeRangeConverter from './TimeRangeConverter';