11

I've created a small app that consists of two main components and I am using vue router to route between components.

First component is called MoviesList and the second one is called Movie. I've registered them in routes js file.

const routes = [
  {
    path: '/',
    name: 'Home',
    component: MoviesList
  },

  {
    path: '/:movieId',
    name: 'Movie',
    component: Movie
  }
  
]

And my App.vue template looks like this

<template>
   <router-view></router-view>
</template>

How can I make MovieList component cached or so to say like it is wrapped with <keep-alive> tags? Desired outcome would be to make MovieList component cached and Movie component not.

I want to do that because MovieList component has a method that runs on mounted() hook and whenever I switch routes and come back that method runs again because component is re-rendered.

Ackroydd
  • 1,482
  • 1
  • 13
  • 14
Pavo Gabrić
  • 179
  • 2
  • 4
  • 8

3 Answers3

18

try this include="MoviesList",or exclude="Movie" also work

<router-view v-slot="{ Component }">
  <keep-alive include="MoviesList">
    <component :is="Component" />
  </keep-alive>
</router-view>
tanqy
  • 181
  • 2
  • 5
    Make sure your component has a name set (`export default { name: '...'}`) - the default name based on the component filename won't work. Also, more info on the router-view new slot api is here: https://next.router.vuejs.org/api/#router-view-s-v-slot –  Sep 13 '21 at 14:54
  • 3
    Also - if you use script setup you need to add another ` –  Sep 13 '21 at 15:04
7

Try to use keep-alive inside router-view and render it conditionally based on the current component :

<router-view v-slot="{ Component }">
 <template v-if="Component.name==='movie-list'">
    <keep-alive>
      <component :is="Component" />
    </keep-alive>
 </template>
<template v-else>
     <component :is="Component" />
</template>

</router-view>
Boussadjra Brahim
  • 82,684
  • 19
  • 144
  • 164
1

For Vue.js 2.0, this example helped me a lot!

https://jsfiddle.net/Linusborg/L613xva0/4/

Basically, the key is to make sure you use the component name in the include:

<keep-alive include="componentname">
  <router-view></router-view>
</keep-alive>
const MyComponent = {
  name: 'componentname',
  template: '<div>My awesome component!</div>'
}

const routes = [
  {
    path: '',
    component: MyComponent
  }
]
dstran
  • 47
  • 7
  • New link https://jsfiddle.net/kgcupret/7/ because in old VueRouter is undefined (URL for its is not working now) – mikep Feb 10 '23 at 15:34