sandip kakade
sandip kakade

Reputation: 1356

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.

Upvotes: 2

Views: 615

Answers (2)

LiranC
LiranC

Reputation: 2480

No. There is no need to generate a new Vue instance.

Generally speaking, only single Vue instance should exist in your application.

Special Use cases that might lead you to create multiple Vue instances:

  • Event Bus: It requires a new Vue instance.
  • Mounting Vue instances on different parts of your legacy DOM. You never need this if you create Vue application from scratch.

I highly recommend you to take a look at high-quality solutions (templates) that are already made up for you and maintained by a large community, before taking decisions that has already been addressed.

Upvotes: 1

Kumar_14
Kumar_14

Reputation: 584

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.

Upvotes: 2

Related Questions