vue.jsvuejs2vue-componentvue-routervue-resource

Difference between calling new Vue() from main.js V/s calling from each and every component


I have a project where I have initialized new Vue() from main.js using #app.mounted.

Thereafter I have injected all router views from each and every component into the app.

Now, what I am thinking is I should call new Vue() in each and every component instead of calling from one central main.js file.

I am asking if this approach of calling/importing Vue and initializing from each and every file is a good approach or should I stick to initialize from one central file.


Solution

  • It is perfectly valid to include multiple Vue instances, there is nothing wrong with that, as long as they are self-contained and and didn’t rely on other Vue instances. It’s still fine to access Vue instances after they have been initialized, because this doesn’t break the principle of loose coupling, and they can therefore still be isolated from each other.

    Adding two Vue instances to the same page, which operate on different parts of the DOM. This is very useful for adding widgets to a page, eg, one Vue instance would be responsible for a form on the right hand side of the page, and another would control the navigation.

    But, as it's not a big problem at a small scale, it can quickly lead to code that is very hard to maintain. Because your Vue instances would no longer be isolated from each other, it can be very hard to figure out the dependencies between them, and changing something in one Vue instance could easily break another.I just want to recommend that you stay away from this approach.

    Single Vue instance bound to the whole page and do all of your logic in one component, that can get messy very fast. It all depends on what you're trying to achieve, but vuex can help keep your state in order while using multiple components.