Vuejs: Lifecycle hooks of child routerview components using keep alive

∥☆過路亽.° 提交于 2019-12-23 10:15:54

问题


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()


回答1:


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://vuejs.org/v2/api/#keep-alive

Update using: npm update --save vue



来源:https://stackoverflow.com/questions/43735371/vuejs-lifecycle-hooks-of-child-routerview-components-using-keep-alive

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!