Storing a variable in session storage using Vue/Nuxt for persistent data

I am currently utilizing the Google Maps Javascript API to create a map object on my website. The challenge I am facing is that every time I navigate between pages and return to the map page, the map object gets reinstantiated unnecessarily, resulting in additional API calls. In vanillaJS, I would typically create a global variable for the map.

I am curious about how I can maintain the map object within the session so that revisiting the map page recalls the existing map instead of creating a new one.

The structure of my code resembles the following...

<template>
  <div>
    <div id="map"></div>
  </div>
</template>

<script>
methods: {
    onScriptLoaded() {
      console.log("Maps API Triggered");
      this.map = new window.google.maps.Map(document.getElementById("map"), {
        center: new window.google.maps.LatLng(somelat, somelng),
        zoom: 11,
        ...})
    }

mounted(){
if (!process.server && !window.google) {
      const script = document.createElement("script");
      script.onload = this.onScriptLoaded;
      script.type = "text/javascript";
      script.src =
        "https://maps.googleapis.com/maps/api/js?key=<API KEY>&libraries=places";
      document.head.appendChild(script);
    } else {
      this.onScriptLoaded();
    }
}
</script>

When returning from a different route (e.g., /about), this.map is reset to undefined and gets reinitialized when visiting the map page again.

Is there a method to persist the this.map object so that it retains the map data when coming back to this page?

Answer №1

If you're utilizing vue-router, it's possible to optimize performance by caching the components that are routed using keep-alive.

  <keep-alive>
    <router-view />
  </keep-alive>

This method caches all routes. If you prefer to cache only a specific component, you can use include:

  <keep-alive :include=['mapComponent']>
    <router-view />
  </keep-alive>

Please note: 'mapComponent' should be replaced with the actual name of your component, not the route itself.

Alternatively, you have the option to cache the component directly like this:

<keep-alive>
  <map-component></map-component>
</keep-alive>

By implementing keep-alive, the mounted hook will only get called once, right after the component is created. To execute specific actions when navigating to or from the route, utilize the activated() and deactivated() hooks.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Error encountered while parsing a file: JSON parsing failed due to an unexpected token 'g' at position

https.get('example.com/phpfilethatechoesandimtryingtograbtheecho.php', (res) => { console.log('statusCode:', res.statusCode); onsole.log('headers:', res.headers); res.on('data', (d) => { return ...

How to use jQuery to select an element by using 'this' on a button

I have a total of 5 divs, each containing 5 different texts. <div class="text"> <%= theComment.text %> </div> I am working with node.js, MongoDB, and Mongoose. In addition to the divs, I also have a button labeled EDIT with a cl ...

Embed the json data within the modal box

I received a JSON response from a php function, and it looks like this: [{"id":"15","activity_type":"call","activity_title":"Call to check "}] Below is the script that triggers the request (actvitiy.js) (Edited) $(document).on("click", ".view_contact_ac ...

Set a unique color for the background of the button when it is clicked

I am looking to enhance my previous post by adding a background color to the button upon clicking. My attempt with btn[i].style.background = "#000000" did not work as expected. <script> const btns = document.getElementById("container"); const textBt ...

The Colorful World of CSS Backgrounds

I've been searching for hours trying to track down the source of this strange greenish background color. I've combed through every single file and it's starting to drive me insane. Any ideas where this color could be coming from? I highly d ...

Receive Real-Time Notifications -> Update Title Using an Array Retrieved from a JSON File

I've been working on updating a live chart every 5 seconds with new data from the database. While I could easily update the information, I encountered a problem when trying to set a path within the chart options for tooltips callbacks afterTitle. Spec ...

Capture user input from an HTML text input element and store it in a JavaScript variable

I am attempting to capture a text value entered by the user, store it in a JavaScript variable, and then use it in mathematical functions after additional input. In order to achieve this, I need to first store the inputs as variables. The ID of the input f ...

No value is stored in the Javascript variable

https://i.sstatic.net/iE5N5.png I am currently using an xml file as a database for my website, with a table that displays all the products. Adding a product to the xml automatically updates the table (refer to the image). Now, I want to implement the func ...

Strategies for smoothly navigating the page to a specific div every time

Currently, I am working on a form that requires submitting multiple child forms. To enhance user experience, I have incorporated jQuery functionality to display a message at the top of the page upon each submission. Now, my goal is to implement a feature w ...

Activating a concealed button to enable the Fullscreen API with each visit to a page

My goal is to initiate full screen-mode using a hidden button every time the page loads. This project is intended for a private webapp, not the public web, and after logging in, it should automatically switch to fullscreen-mode. Currently, my workaround is ...

Creating an interactive timer that counts down in real-time using a combination of Django and JavaScript

When passing the date and time from views.py to my HTML page, I am encountering difficulties in utilizing that information to create a countdown timer using Javascript. For example: return render(request,'page.html',{'date':i.date,&apo ...

The comments entered into the box are being overridden instead of being posted

I have encountered an issue where, upon hitting the post button, the comment is successfully posted on the page. However, if I hit the button again, it seems to override the previous comment. Can someone please provide clarification on this matter? Additio ...

How can I access the post-AJAX version of the browser using Zombie.js pressButton?

Utilizing zombie.js for automated testing of browser actions involves simulating clicking on a button to submit a form. However, in the real browser environment, this action triggers an AJAX request that dynamically adds two div.alert elements to the docum ...

Accessing a service instance within the $rootScope.$on function in Angular

I'm looking for a way to access the service instance variable inside the $rootScope in the following code. myapp.service('myservice',function($rootScope) { this.var = false; $rootScope.$on('channel',function(e,msg) { v ...

Transformation of Object into Number through Function Execution in Javascript

I am currently facing an issue with my animate() function while using Three.js to generate an animation. Below is a simplified version of the code: let obj; let camera = new THREE.PerspectiveCamera(fov, asp, near, far); let scene = new THREE.Scene(); const ...

Is there a way to render dynamic components in Vue similar to JSX?

When working with jsx, it is possible to store components in variables using syntax like const comp=<p>Hello</p>. This allows flexibility in rendering components by choosing which one to use. I am curious if there is a similar capability in Vu ...

Instantly reveal menu by pressing button

Is there a way to make my mobile menu open immediately upon touching the button? I have used ontouchstart="" in both buttons to create an overlay on the content when the offcanvas menu is visible. This functions well as soon as the user touches either butt ...

Angular Controller encounters issue with event handler functionality ceasing

One of my Angular controllers has the following line. The event handler works when the initial page loads, but it stops working when navigating to a different item with the same controller and template. document.getElementById('item-details-v ...

Ways to run a controller prior to loading the templateUrl

How can I run a controller before loading the step1.html page? (function () { "use strict"; var app = angular.module("autoQuote",["ui.router","ngResource"]); app.config(["$stateProvider","$urlRouterProvider", function($stateProvider,$urlRout ...

JavaScript can retrieve the default page name that is hidden within the browser's URL

When a URL is entered without a specific file name at the end, such as "www.google.com," the server typically serves a default file like "index.html" or "default.aspx." In this scenario, if the browser displays "www.google.com," I am looking to extract the ...