Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make certain component "keep-alive" with router-view in Vue 3?

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.

like image 677
Pavo Gabrić Avatar asked Jan 07 '21 20:01

Pavo Gabrić


People also ask

How do I create a dynamic route Vue?

Adding dynamic routes in VueUpdate the router/index. js file with the new route in the routes array. Remember to include the import for the Post component. Restart your app and head to localhost:8080/post/dynamic-routing in your browser.

What is keep alive in Vue?

<KeepAlive> is a built-in component that allows us to conditionally cache component instances when dynamically switching between multiple components.


2 Answers

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>
like image 51
tanqy Avatar answered Oct 31 '22 03:10

tanqy


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>
like image 38
Boussadjra Brahim Avatar answered Oct 31 '22 03:10

Boussadjra Brahim