Component without template

LeBlaireau picture LeBlaireau · Apr 17, 2018 · Viewed 9.6k times · Source

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?

Answer

skribe picture skribe · Apr 17, 2018

I would suggest using a mixin here.

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

export default {
   methods: {
      myAwesomMethod() {
         //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://vuejs.org/v2/guide/mixins.html