简体   繁体   中英

VueJS - render component only once

Is it possible to have a component that would only ever be rendered/instantiated once and the same instance could be used by other components?

I'm using the npm Google Maps library in my project, and I want to have a single map instance rather than having to render it every time, which is using a lot of memory.

The below code shows the object that I'd like to be instantiated only once, as part of the component:

private googleMap: google.maps.Map;

    mounted() {
        this.googleMap = new google.maps.Map(document.getElementById('map'), myMap.options);
    }

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM