[Vuejs]-VueJS – render component only once

2👍

Instantiating component once and Rendering component once are two different things.

Rendering component once is meaningless to think about. Render function will always be called whenever any prop or instance property is changed.

Instantiating component once is a very common scenario. Components like snackbar, dialog box, alert notifiers are often instantiated once.

To instantiate component once, there are two things you can do. First, make this component child of root instance or somewhere at the top of a component hierarchy like:

// Root Instance Template
<app-component>
    <header></header>
    <router-view></router-view>
    <google-map></google-map>
</app-component>

Next option is to manually instantiate and mount this component alongside the root Vue instance. Then, inject this component into your application hierarchy. You can do something like:

const mapComp = new Vue({ name: 'google-map' })
    .$mount(document.querySelector('.map'));

// Pass mapComp to rootInstance which can then inject into children component.
const rootInstance = new Vue({ /* options */, mapComp })
    .$mount(document.querySelector('.app'));

There are pros and cons of both the approaches but generally, the first approach should be preferred.

1👍

use vuex store to store your googleMap object and pass a reference to it to your component as props (recommended). that way, you can render your component a few times, but their googleMap prop will refer to your single googleMap object in the store.

i dont think its possible in vuejs to render a single component in different places in your app.

Leave a comment