Languages

Nuxt 3 - how to create a function in another file and import it?

0 points
Asked by:
Gigadude
791

How can I create some utils in Nuxt 3?

I need to create a function in a separate file and import it in my main index.vue file.

1 answer
0 points
Answered by:
Gigadude
791

1. Create assets/ directory in the main project file, then create utils.js file inside.

2. Inside the utils.js file you can create and export some functions like:

const utils = {
    function1() {
        console.log('Hello from function1');
    },
    function2() {
        console.log('Hello from function2');
    },
};

export default utils;

3. Now in the index.vue file inside the <script> element:

  • use import keyword to import the utils,
  • call functions from imported utils using utils.functionName().

Practical example:

<template>
    Check the console using F12
</template>

<script>
import utils from '~/assets/utils';

utils.function1();
utils.function2();
</script>

<style scoped>
/* ... */
</style>

Result:

Nuxt 3 - create and import function from another file

0 comments Add comment
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join