Vue-router reloads page and I lose my state, how do i avoid this?

Ann HB picture Ann HB · Jun 10, 2018 · Viewed 7.3k times · Source

I have a form divided in 5 components and the user can navigate through them via steppers (I'm using vue-material for my project). I use vue-router for that. However, I'm having a serious issue here: components lose all the information in the store (I'm using vuex) when they come back to a route they already filled. So to make it clear: if a user fills the first step of the form and then goes to step two, when he wants to come back to step one data is no longer available and the form is totally empty (and the state in vuex is also reset). What am i doing wrong?

import Vue from 'vue'
import Router from 'vue-router'
import Projet from '@/components/Fiches/Projet/Projet'


Vue.use(Router)

export default new Router({
routes: [
{
  path: '/',
  name: 'Home',
  component: Projet
},
//other routes here
]
})

And this is the html code

<template>
 <div class="project-steppers">
   <md-steppers md-dynamic-height md-alternative>
      <md-step id="first" to="/Projet" md-label="Projet" />
       // other steps here
    </md-steppers>
  </div>
</template>

And an example of one of the inputs I use:

      <md-field>
        <label for="project-name">Nom du projet</label>
        <md-input id="project-name"
                  v-model="project.projectName"
                  name="project-name"
                  @change="updateProjectName"/>
      </md-field>

[...]
  methods: {
updateProjectName () {
  this.$store.commit(projectStore.MUTATE_PROJECTNAME, this.project.projectName)
}

More information: when I fill the different inputs I see that the store is updated with the new values, so the mutation is working.

Answer

alansaldivar picture alansaldivar · Jan 25, 2019

First of all, Vuex does not store data in the browser - just in memory. That means that you could either install a third party plugin such as vuex persisted state or write your own methods to set and get the items from your storage, e.g.:

const storage = localStorage.getItem('key');

new Vuex({
   state: {
     yourProp: storage ?
        ? JSON.parse(storage.yourDataKey)
        : 'default-value'
   },
   actions: {...}
   mutations: {...}
})