jlmmns's avatar
Level 12

New Vue instance for every component?

Hi all,

I'm just getting started with Vue, but I can't find a direct answer for a very basic question.

Every time I see a Vue tutorial, it starts off with a Vue instance on <div id="app"> as the root element.
But is it considered as the root element for a specific component, like a list?
Or is it the root of your entire page/application?

So, is it better to have only one new Vue(), and store every model data from several components inside that one instance?
Won't this get messy and difficult to maintain?

// include on every page?
new Vue({
    el: '#app',
    data: {
        profileData   : {...},
        teamData      : {...},
        dashboardData : {...},
        ...
    }
})

Or do it like this?

// on same page
new Vue({
    el: '#dashboard-view',
    data: {
        dashboardData : {...}
    }
})
new Vue({
    el: '#profile-component',
    data: {
        profileData : {...}
    }
})
new Vue({
    el: '#team-component',
    data: {
        teamData : {...}
    }
})
0 likes
5 replies
bobbybouwmann's avatar
Level 88

You only need one Vue instance. You can then create components and use them instead

Vue.component('counter', function() {
    // Your component stuff
});

new Vue({
    el: '#app'
});

You can now use the counter component in the div that has the id app

1 like
jlmmns's avatar
Level 12

@bobbybouwmann So I could do the single Vue instanciation in my main.js file, for example?

How would I add the right components according to a specific page?
So it would be better to put the Vue instance on my page, and all my components in a components.js file?

bobbybouwmann's avatar

Not sure, I don't have much experience with Vue. The basic idea is that you create components so you can reuse them. For a component to work you need at least a Vue instance.

I guess you can just create all components in one file or in multiple files, shouldn't really matter!

1 like
jlmmns's avatar
Level 12

@bobbybouwmann You're right. I just need to figure out how to structure my files and how to include them.

I was thinking of having one file per component (eg: components/task_list.js), and then include it on pages where needed.
And if I have many components on a single page, I could maybe combine them with the main view js file, with Elixir.

Thanks for your input, Bobby!

frlzjosh's avatar

I have this instance where I am using vue-router on only a few pages/components however this is overriding my root because everything points back to el: '#app' in my app.js. I tried making another el: #spa with my spa components in there, but it still overrides my other pages that has a vue component in my blade views.

Please or to participate in this conversation.