27

I have a bit of code that makes an api call to a server and returns some JSON.

It did exist as a method in my component but as it is getting a bit long I want to extract it to it's own file

In vuejs what is the best practice here.

  • should it be a component without a template? How would this work?

  • will I just create an es6 module?

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
LeBlaireau
  • 17,133
  • 33
  • 112
  • 192

2 Answers2

25

I would suggest using a mixin here.

In a file like myCoolMixin.js define your mixin...

export default {
   methods: {
      myAwesomeMethod() {
         //do something cool...
      }
   }
}

You can define anything in a mixin just like a component. e.g. data object, computed or watched properties, etc. Then you simply include the mixin in your component.

import myCoolMixin from '../path/to/myCoolMixin.js'

export default {
   mixins: [myCoolMixin],
   data: function() {
      return: {
         //... 
      }
    },
    mounted: function() {
       this.myAwesomeMethod(); // Use your method like this!  
    }
 }

More on Mixins here: https://v2.vuejs.org/v2/guide/mixins.html

tony19
  • 125,647
  • 18
  • 229
  • 307
skribe
  • 3,595
  • 4
  • 25
  • 36
  • Important note about mixins : it affects ALL components & sub-components. While it works as a global library for the project (methods only), having processing inside mixin's "mounted" or "created" hooks would execute that processing script as many times as the number of loaded components & sub-components for all mounted entrypoints – Raywell Mar 17 '20 at 08:11
  • 2
    @Raywell You're confusing this with a [global mixin](https://vuejs.org/v2/guide/mixins.html#Global-Mixin). If you add the mixin like in this answer - via `mixins: [myCoolMixin]` - then it will only be added to that component. – Raphael Schmitz Jul 10 '21 at 08:28
2

Mixins work, or you could create a plugin. Here's the docs example:

MyPlugin.install = function (Vue, options) {
  // 1. add global method or property
  Vue.myGlobalMethod = function () {
    // something logic ...
  }

  // 2. add a global asset
  Vue.directive('my-directive', {
    bind (el, binding, vnode, oldVnode) {
      // something logic ...
    }
    ...
  })

  // 3. inject some component options
  Vue.mixin({
    created: function () {
      // something logic ...
    }
    ...
  })

  // 4. add an instance method
  Vue.prototype.$myMethod = function (methodOptions) {
    // something logic ...
  }
}

Vue Plugins

Sadra Saderi
  • 52
  • 1
  • 8
Brian Lee
  • 17,904
  • 3
  • 41
  • 52
  • Like the answer and will definitely look into plugins, though I think mixins are a better fit here. Thanks. – LeBlaireau Apr 17 '18 at 09:40
  • I tend to favor mixins personally, plugins I only opt for when i have a large feature set sharing commanility – Brian Lee Apr 17 '18 at 09:51