Search code examples
vue.jscross-platformelectronstatedesktop-application

Saving state on back button press in vue-electron


I want to make a desktop app in vue-electron. I am new to both vue.js and electron. I am having some problems while managing state.

When I click on login button https://cloudup.com/cFl9MTY6cnn I send data i.e sessionId and username to next screen https://cloudup.com/c76fmL8OGbF and on this screen I display these props https://cloudup.com/csahnc6Z04J using this code https://cloudup.com/cdR0F6Qyt-3 but as I go to the third screen https://cloudup.com/c0F1ztX8qu3 and then come back then this data disappears https://cloudup.com/cTFW32DxeRa

I am going back to second screen using router.go(-1) https://cloudup.com/cvpxk4GsIRx

The vue-router documentation https://router.vuejs.org/en/essentials/navigation.html says that “router.push method pushes a new entry into the history stack, so when the user clicks the browser back button they will be taken to the previous URL.” and router.go(n) "This method takes a single integer as parameter that indicates by how many steps to go forwards or go backwards in the history stack"

However in my case, lifecycle hooks are called again when I go back to history stack. So does that mean when we come to previous page that component is created again and not popped from stack. I actually don’t want to refresh / reload the page on back button.


Solution

  • You need to send the data to the third screen,too.

    Instead of

    <route-link to="third_screen"></router-link>
    

    You need to write,

    <router-link :to="{ path: 'third_screen', params: { session_id: this.session_id, userName:this.user_name}}">User</router-link>
    

    And instead of router.go(-1) you need to send the data as params again to your second screen using router.push() method.

    But I won't suggest the above method as you need to pass the same data as params to all routes.

    You should also have a look at Vuex.

    Vuex is a state management pattern + library for Vue.js applications. It serves as a centralized store for all the components in an application, with rules ensuring that the state can only be mutated in a predictable fashion.

    You should store your Session Id as cookie instead of passing it as props.

    Update

    Also have a look at <keep-alive></keep-alive>.

    Reference