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.
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.
Share Improve this question edited Jan 17, 2021 at 23:31 Ackroydd 1,6101 gold badge13 silver badges14 bronze badges asked Jan 7, 2021 at 20:03 Pavo GabrićPavo Gabrić 2092 gold badges5 silver badges8 bronze badges3 Answers
Reset to default 22try this include="MoviesList"
,or exclude="Movie"
also work
<router-view v-slot="{ Component }">
<keep-alive include="MoviesList">
<component :is="Component" />
</keep-alive>
</router-view>
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>
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
}
]