Navigate between pages using Leaflet.js + Vue.js - memory leak issue solved
P粉649990273
P粉649990273 2024-01-08 13:39:55
0
1
564

I'm trying to make a Vue.js application containing many Leaflet maps.

The following jsfiddle is an example of the application I'm trying to create:

https://jsfiddle.net/RayLa/vr2b6ad7/126/

The specific map components are as follows:

const MapComponent = {
  template: '<div id="map">About</div>',
  mounted(){
    let map = L.map('map').setView([51.505, -0.09], 8);
    L.tileLayer('https://tile.openstreetmap.org/{z}/{x}/{y}.png').addTo(map);
    
    fetch("https://raw.githubusercontent.com/martinjc/UK-GeoJSON/master/json/administrative/gb/lad.json")
      .then((response) => response.json())
      .then((data) => {
        L.geoJSON(data).addTo(map);
      })
  }
};

The application contains two pages, a "Home" page and a "Map" page. The Maps page contains leaflet maps. The application looks like this:

The problem is that when I navigate from the Map page to the Home page and back again, there seems to be a massive memory leak. From the Chrome Developer Tools, under the Memory tab, the amount of memory used by the application on startup is shown below (73.8MB):

When I click multiple times from the "Home" page to the "Map" page, the amount of memory used by the application is as follows (739MB):

If I keep clicking between the two pages, the app will eventually crash due to lack of memory. I can't seem to figure out the cause of the memory leak.

How to unload a component so that all related data is cleared from memory?

Does anyone know how to solve this problem? I'm not sure if this has to do with Leaflet.js for Vue.js.

P粉649990273
P粉649990273

reply all(1)
P粉340264283

I'm no vue expert, but I'm pretty sure the problem is that you're not destroying the leaflet map properly. You must call map.remove() (https://leafletjs .com/reference.html#map-remove), otherwise the DOM node holding the map will remain in memory, Even if your component is long gone.

Once you navigate back to the home page, vue router will destroy your MapComponent and you can use the destroyed lifecycle hook to delete its leaflet map. See this fiddle: https://jsfiddle.net/wuo15b4L/

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!