[Vuejs]-If user navigate to different screen or logout the session the entered form data should not vanis

0👍

What I think you are trying to do is when a user has not submitted the form and has left the page you want it to reload the data. For this you can use localstorage. If you want it to load the data in from the server, then you would need to make a call to the server and get the data back, then load it in with the mounted life-cycle hook.

What you would want to do is hook into the Vue instance before it is destroyed by using the beforeDestroy life-cycle hook. Then you would want to save the data to localStorage. First, you would want to grab all the data you want to save or the entire data object (by using this.$data), and convert that to JSON as localStorage cannot accept complex datatypes. Then you would commit that to localStorage like so:

beforeDestroy(){
    localStorage.formSave = JSON.stringify(this.$data);
}

Next time, when the user opens the page you want to get all the data from localStorage and load it back to an object. We will need to use JSON.parse() to convert it from a string into an object. For this, we will use a loop so we can ensure that if the data object has had fields added we are not overwriting it. For this we will tap into the the mounted life-cycle hook.

mounted(){
   let dataFromLocalStorage = JSON.parse(localStorage.formSave);
   for(const key in dataFromLocalStorage){
      this.$data[key] = dataFromLocalStorage[key];
   }
}

If you want to protect against refreshes as well you can add onbeforeunload this will catch reload events before they happen. Then you can call $destroy() to manually trigger the destroy lifecycle. You would either add this to the created life-cycle hook or the mounted life-cycle hook.

window.onbeforeunload = () => this.$destroy();

Here is a working example on codesandbox

Leave a comment