Where to put custom Vue mixins and helper functions in a Nuxt project?

Viewed 2976

I have a Nuxt project and I need to make custom functions and Vue mixins to reuse in Vue components and pages.

In which folder should I put the files containing these? Should I create a 'lib' folder at the top level of the Nuxt project and put the files in there?

Extra details if that can help:

  • These functions will be imported only when needed (not global)
  • These functions will be tested

Nuxt Directory Structure Documentation

3 Answers

in my nuxt project, I usually add four folders at the root directory level of the project which is mixins for all of my mixins, models for the models or classes which I use throughout the app, services which contains all my API's endpoints and utils which contains all my utility functions and other general functions like my input's validation functions and my directory looks like this:

enter image description here

in the case of mixins you can then import the required mixin into the desired component and use them like you normally would:

import someMixin from '@/mixins/someMixin'
...
export default {
  mixins: [someMixin],
  ...
}

you can put the mixins file into 2 folders.

  1. you can create global-mixin.js into the plugins folder and after that set this file into plugins: [] part in nuxt.config. link
  2. you can create a mixins folder and create mixin.js into that. link

But the nuxt.js's documents suggested that the first solution was correct

As Nuxt has not any specific directory for mixins, you can create them like any other plugin you have in your project. I prefer to have my overly used plugins in a folder named common. It is your choice really. But as you want to reuse them throughout your project, then you may want to use global mixins, which are similar, But they can lead to memory leakage when not handled correctly. So we need some kind of flag to prevent it from registering multiple times.

Therefore, create a directory you like (for example myMixinFolder). For example I am going to create a mixin file. I create a file inside myMixinFolder and name it my-mixin-plugin.js.

import Vue from "vue"

if (!Vue.__my_mixin__) {
  Vue.__my_mixin__ = true
  Vue.mixin({ 
    methods: {
      sayIt(name) {
        console.log(`Hello dear ${name}`)
      }
    }
  })
}

Then add it to nuxt.config.js file:

plugins: [
    { src: '~/plugins/my-mixin-plugin.js' },
],

Now you can use it in any component like this:

<template>
  <span>{{ sayIt('Batman') }}</span>
</template>

Or inside script:

this.sayIt('Batman')

This way you don't need to import mixins again and again (Although, you need to be careful if you have more than one mixin file to prevent memory leakage).

Related