Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Refresh pages in vue.js keep-alive section

I have a Vue.js SPA that uses vue-router. because after logging in each page needs to keep state (like filters/pagination entered) This is done using keep-alive:

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

This works very well but when somebody logs out and logs in again I still see the same filter values due to the keep alive.

Can I refresh/purge the pages kept alive programatically somehow at logout?

like image 533
Ritsaert Hornstra Avatar asked Oct 24 '18 11:10

Ritsaert Hornstra


People also ask

How do you refresh a page in Vue?

window. location. reload(); The following line of code outlines the various methods that can be utilised in order to find a solution to the Vue Js Reload Page problem.

How can you prevent layout jumps in VUE JS?

Use single file components if you can. If you come from React you can also find jsx for Vue useful, or even write render function by hand (though not recommended). If you want to totally nullify the time of the first rendering though, the only way to go is to do server-side rendering.


2 Answers

I don't think there is an easy way to do this(programmatically) so you are left with 2 options.

Options 1 would be to reset the state which means you internally keep track of the initial state and listen for something like an emit on logout to reset the component to its initial state.

Option 2 would be to simply swap out the keep-alive component using something like this:

<keep-alive v-if="loggedIn">
    <router-view></router-view>
</keep-alive>

<router-view v-else></router-view>
like image 148
Stephan-v Avatar answered Sep 28 '22 10:09

Stephan-v


One way you can use Vue global event.

Vue.prototype.$loginState = new Vue();

In your component fire the event on click logout button.

function logout(){
    //your codes here to logout and then
    this.$loginState.$emit('logout');
}

In component which user sees when logged in just set all variables to their default values by listening event fired 'logout'.

<button @click="resetValues"> Logout </button>
methods: {
    resetValues(){
        this.yourValue = '';
        this.filters = [];
    }
}
created(){
    this.$loginState.$on('logout', this.resetValues)
}
like image 31
WebMan Avatar answered Sep 28 '22 08:09

WebMan