Felix
Felix

Reputation: 2661

Should I be storing all my Vue methods and data in one file?

I'm currently using Vue on my web app for object oriented form validation, so that all I need is back-end validation and vue takes care of the rest.

This means that if my app has a lot of forms, forms that are mostly just page specific, I end up with a lot of methods and data in my Vue instance.

new Vue({
    el: '#mainDiv',

    data: {
        profile_text: '',
        name: ''
        //LOTS OF DATA THAT I'M LEAVING OUT
        errors: new Errors()
    },


    methods: {
        onSubmitSettings() {
            axios.post('/settings', this.$data)
                .then(response => alert('Success!'))
                .catch(error => this.errors.record(error.response.data.errors));
        },
        onSubmitCreate() {
            axios.post('/subchannel/create', this.$data)
                .then(response => alert('Success!'))
                .catch(error => this.errors.record(error.response.data.errors));
        }, 
        //LOTS OF METHODS THAT I'M LEAVING OUT
    }
});

and this is all stored in one JS file.

Should I keep doing it like this? Or should I be storing methods/data meant for only one page to be stored on that page somehow?

Upvotes: 0

Views: 177

Answers (1)

Harshal Patil
Harshal Patil

Reputation: 21030

Assuming that the code you shared is your main/root Vue instance, it probably is a bad practice to put all these in a single component.

Ideally, your code should have segregation of components between views and components. views are like individual pages which contain most of the business logic whereas components are reusable items like checkboxes, lists, inputs, etc..

The reasons for dividing the app into smaller views are:

  • Putting everything in a root instance will make your components less-reusable. They are depending on some sort of global state.
  • This makes modifications harder to track; overall making code less maintainable within the team.
  • Splitting into smaller views/components will allow you to use other ecosystem tools like vue-router which will further help in maintaining URLs, URL history, etc.
  • Segregation into smaller components will enable Vue.js to better track change detection producing efficient and performant view updates. UI updates become significantly faster.

In a nutshell, it is about following classical software engineering principles like SOLID, loose coupling, etc. This, in general, is not just confined to Vue.js.

Upvotes: 3

Related Questions