Search code examples
vue.jsvuejs2vue-componentvue-routerkeep-alive

Vue Keep-Alive - Component App Header won't stay alive during route changes


I defined the main page of my vue app to look like this:

<div class="wrapper">
    <keep-alive>
      <app-header></app-header>
    </keep-alive>
    <router-view></router-view>
</div>

<script>
import appHeader from '../components/Header';

export default {
  components: {
    appHeader
  }
/* etc... */
}

My app UI is basically starting from this component, with many different routes and sub-routes paths to show many pages, but in all pages (components) I want to show the app-header at the top of the page.

The problem is that I noticed recently, with every button clicked (that changes vue-router's route to another page), the app-header gets recreated (the created() lifecycle hook function is called)

I really don't understand why, since I added keep-alive, shouldn't it be rendered once?

Please help me figure this out, I am stuck, I literally researched the entire internet about it.

Please note! I don't want the routes to stay alive, only the app header itself

Here are links to view more of my code, which could might help you understand better:

1) App.vue (Pastebin)

2) Dashboard.vue (Pastebin)

3) Router files (Pastebin)

Please note that at main.js of Vue I import the router and put it first parameter in an object like "new Vue({router, store, vuetify, render: h => h(App)}).$mount('#app');". "App" is an import of App.vue posted, and vuetify is a plugin you all probably know already. Please let me know if you need anything else, I really appreciate your help!!

Thanks in advance


Solution

  • <keep-alive> is for saving the state of dynamic components i.e <component :is="myComponent">

    Use <router-link to="/myroute"> or $router.push('/myroute') to move between routes and the non dynamic components outside the router-view will maintain their state.

    Here's a simple demo: https://jsfiddle.net/ellisdod/uzj8317m/