user2543127
user2543127

Reputation: 415

Vue Js: How to separate 'methods', 'data', 'computed' etc..in separate js files

is it possible to write methods,data,computed, etc.. in separate .js files then importing them in a component.vue file?

I would not put all js logic in one single .vue component.

For each component, i want organize the code in this way:

myComponent/
      component.vue
      methods.js
      data.js
      computed.js
      etc..

Then in component.vue:

methods: ()=> from './methods.js'

I Just tried with module export but It doesn't works

Upvotes: 5

Views: 2909

Answers (2)

Armand
Armand

Reputation: 2827

I'd recommend using mixins instead.

Mixins provide quite a powerful way of dealing with externalised code meaning you don't have to segregate logic across different files (i.e. data.js, methods.js, etc.)

Instead, you can keep all logic related to one particular feature in one file (mixin) and then inject it into your component, or even several components if you find your code reusable.

Also, very important to note, mixins preserve standard Vue js lifecycle method functionality.

myMixin.js

export default {
  data() {
    return {
      myData: ''
    }
  },
  methods: { ... },
  created() { ... },
  mounted() { ... },
  etc...
}

https://v2.vuejs.org/v2/guide/mixins.html

Upvotes: 1

Sumurai8
Sumurai8

Reputation: 20737

Just export the objects and functions, then import them in the component.

// methods.js
export default {
  myMethod () {
    console.log('a');
  }
}
// data.js
export default function () {
  return {
  }
}
// computed.js
export default {
  myVariable() {
    return '';
  }
}
// component.vue
import methods from './methods';
import data from './data';
import computed from './computed';

export default {
  ...methods,
  ...data,
  ...computed
}

Upvotes: 12

Related Questions