0
votes

I have issue with having keep-alive actually keeping components alive.

Component that is being rendered in router-view have async fetching after component is mounted. My issue is that after the first time component shows up, when I render other component in that very same router, and then go back, then first component rerender as normal instead of keeping fetched data as it was.

I checked hooks and besides activated and deactivated also created hook fires which I suppose shouldn't be the case beyond first render. Also when I switch components destroyed hook fires which also shouldn't happen.

.container-fluid
  .row.wrapper
    aside.col-12.col-sm-2.p-0
      nav.navbar.navbar-light.navbar-expand-sm.align-items-start.flex-sm-column.flex-row.text-uppercase#navbar1
        a.navbar-toggler(href='', data-toggle='collapse', data-target='.sidebar')
          span.navbar-toggler-icon
        .collapse.navbar-collapse.sidebar
          ul.flex-column.navbar-nav.w-100.justify-content-between
            li.nav-item
              router-link.nav-link.pl-0(to='candidates' data-toggle="collapse" data-target=".navbar-collapse.show")
                font-awesome-icon.fa-fw.mr-2(:icon="iconTachometer")
                | Dashboard  

    main.col.bg-faded.py-3
      .card
        .card-body
          keep-alive
            router-view(:key="$route.fullPath")
2
you cannot keep alive functional components - btw duplicate stackoverflow.com/questions/40898440/…, stackoverflow.com/questions/51116961/…Estradiaz
@Estradiaz it's not a functional component. It's a normal one that fetches data when it mounts.jean d'arme
ok was sure its states true: github.com/vuejs/vue-router/blob/… - but nvm must be an optical illusion ;)Estradiaz
vuejs.org/v2/api/#keep-alive just at the end there is a note: <keep-alive> does not work with functional components because they do not have instances to be cached. So despite being functional it works on with non-functional (as far as I read).jean d'arme
yes but as long as you use it like keep-alive \n router-view it wontEstradiaz

2 Answers

1
votes

Okay, I found the answer - and my apologies because turned out my question wasn't fully informed.

First thing - the component in question was already nested within another router-view so what I was actually doing was nesting one in another.

Therefore, to keep alive that nested/child router-view parent router-view also has to be wrapped with keep-alive.

Based on answer here: https://forum.vuejs.org/t/how-to-use-keep-alive-with-nested-router-component/46813/4

0
votes

See Special Attributes - key:

It can also be used to force replacement of an element/component instead of reusing it. This can be useful when you want to:

  1. Properly trigger lifecycle hooks of a component;
  2. Trigger transitions.

If you bind key to $route.fullPath, it will always force a replacement of the <router-view> element / component every time a navigation event occurs. So just remove :key.