1
votes

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 this Dashboard, 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.

Thanks in advance

2
Help please, I really can't figure this one out :(diegorkable759

2 Answers

1
votes

The keep-alive will work only in the section which is wrapped by the <keep-alive> tag. Here, only the app-header component will keep alive. If you need to apply this to all the components within the routes, you have to put the <router-view> inside <keep-alive>.

Eg:

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

Now the keep-alive will work for all the routes.

0
votes

Answer from Rijosh is applicable only for Vue 2 and its router (Router v3.x). If someone uses Vue 3 (and Router v4.x), then code for <keep-alive> and <router-view> looks like this:

<router-view v-slot="{ Component }">
   <keep-alive>
      <component :is="Component" />
   </keep-alive>
</router-view>

More can be found in documentation here.