Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

vue 2 lifecycle - how to stop beforeDestroy?

Tags:

vue.js

vuejs2

Can I add something to beforeDestroy to prevent destroying the component? ?

Or is there any way to prevent destroying the component ?

my case is that when I change spa page by vue-route, I use watch route first, but I found that doesn't trigger because the component just destroy..

like image 794
KevinHu Avatar asked Apr 17 '17 10:04

KevinHu


2 Answers

As belmin bedak commented you can use keep-alive

  • when you use keep-alive two more lifecycle hooks come into action, they are activated and deactivated hooks instead of destroyed

  • The purpose of keep-alive is to cache and to not destroy the component

  • you can use include and exclude atteibutes of the keep-alive element and mention the names of the components that shoulb be included to be cached and be excluded from caching. Here is documentation

  • in case you want to forecefully destroy the component even if its cached you can use vm.$destroy() here

Further you can console.log in all the lifecycle hooks and check which lifecycle hook is being called

like image 67
Vamsi Krishna Avatar answered Oct 17 '22 03:10

Vamsi Krishna


You can use vue-route navigation-guards, so if you call next(false) inside the hook, navigation will be aborted.

router.afterEach((to, from) => {
  if(your condition){
    next(false) //this will abort route navigation
  }
})
like image 4
Saurabh Avatar answered Oct 17 '22 02:10

Saurabh