I'm having some issues updating a reactive object in a Vue.js 3 project. I'm creating an array of google.maps.marker.AdvancedMarkerElement, and I'm creating the array like this:
localizaciones.forEach((localizacion) => {
if (localizacion.agrupaciones) localizacion.agrupacionesF = localizacion.agrupaciones.split(",");
const glyphSvgPinElement = new PinElement();
const glyphImg = document.createElement("img");
glyphImg.src = usingIconsStore.setIcon(localizacion.icono);
glyphSvgPinElement.glyph = glyphImg;
const advancedMarker = new AdvancedMarkerElement({
position: {
lat: localizacion.lat!,
lng: localizacion.lng!
},
content: glyphSvgPinElement.element,
title: localizacion.agrupacionesF![0]
});
advancedMarker.setAttribute("agrupacionesArr", localizacion.agrupaciones);
advancedMarker.setAttribute("id", String(localizacion.id));
advancedMarker.setAttribute("icono", String(localizacion.icono));
marcadores.value.marcadores.push(advancedMarker);
google.maps.event.addListener(advancedMarker, "click", async function () {
infoFichaHelper.value = { marcador: advancedMarker, sugerencia: await pedirDetalleEstacion(props.tipoMapa, localizacion.id) }
});
});
where marcadores is a variable declared like this:
let marcadores = ref<google.maps.marker.AdvancedMarkerElement[]>([])
Then on the first load, my component is to filter this array to get the favourites ones. This array is empty. Is there a way to charge this reactive array on the first load?
Initializing and populating this array within the
onMountedlifecycle hook should help to make sure your reactive array ofgoogle.maps.marker.AdvancedMarkerElementobjects is populated on the first load of your Vue 3 component.That would guarantee that the array is populated after the component has been mounted to the DOM, which should matter for operations that involve manipulating or waiting for external resources like Google Maps.
That means moving the logic that populates the
marcadoresarray into a function that is called within theonMountedlifecycle hook: refactor the population logic into a function:Then call
populateMarcadoreswithin theonMountedhook:After making sure the array is populated on component mount, you can access the filtered or manipulated version of this array as needed in your component.
For example, to filter this array for favorite markers:
Any operation that relies on the populated
marcadoresarray must be executed after the array has been populated. That usually means accessing the array within the template, computed properties, or methods that are triggered by user interaction or other reactive changes that occur after the initial population in theonMountedhook.