Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vuejs: Lifecycle hooks of child routerview components using keep alive

I'll explain my issue in a more generalized way for the purpose of clear understanding and here is the jsFiddle

I have two main routes which show two different components in the router-view

  • Route-1 when clicked the path is: '/route-1'

  • Route-2 when clicked the path is: '/route-2/sub-route-a'

Route-2 contains a another router-view inside it which displays two sub routes that are:

  • sub-route-a

  • sub-route-b

When Route-2 is clicked it opens the component of Route-2 with sub-route-a pre-opened in its router-view

Both the main router-view and the router-view inside Route-2 are wrapped inside keep-alive tag so that they are cached

Caching and everything works fine as expected.

I added all the lifecycle hooks and using console.log to see which hook is called

  • For the first time for all components as expected the beforeCreate() , created(), beforeMount(), mounted() hooks are called.

  • since the router-view is under keep-alive element the activated() hook is also called

  • whenever I move to and fro between Route-1 and Route-2 the activated() and deactivated() hooks are called when entered and left respectively for each component

Here comes my problem

  • Since when Route-2 is clicked it opens the component of Route-2 with sub-route-a pre-opened in its router-view, all lifecycle hooks of sub-route-a componenents are called only once

  • when I go back to Route-1 deactivated() of Route-2 is called but no hook of sub-route-a is called.

  • only when I toggle between sub-route-a and sub-route-b the activated() and deactivated() hooks of these components are called

  • on subsequent entering of Route-2 activated() hook of Route-2 is called but no hook of sub-route-a is called

  • I want to cache sub-route-a but make changes to it on every enter. So where do I put the code since no lifecycle hook is being called excrpt for the first time.

  • **I don't want to use ** beforeEnter()

like image 439
Vamsi Krishna Avatar asked Oct 29 '22 08:10

Vamsi Krishna


1 Answers

Upgrade your vue version to 2.2.0 or greater. The fiddle has 2.3.2, the latest one. And your local version is 2.1.0.

In 2.2.0 and above, activated and deactivated will fire for all nested components inside a tree.

Read here: https://v2.vuejs.org/v2/api/#keep-alive

Update using: npm update --save vue

like image 54
Deepak Avatar answered Nov 12 '22 20:11

Deepak