'beforeDestroy vue dynamic component

How could I add an alert message before switch the component? (beforeDestroy does not work until the path is changed...)

<template>
  <keep-alive>
    <component :is="dynamicComponent" />
  </keep-alive>
</template>


Solution 1:[1]

As you already discovered, when you keep a component alive, it doesn't throw "beforeDestroy" and "created" as normal components, since its being kept alive.

Therefore, Vue has defined other lifecycle methods for this purpose:

  • activated - This gets called when keep-alive loads the component
  • deactivated - This gets called when <keep-alive> unloads the component

You use them like this:

export default {
    created() {
        console.log('created');
    },
    activated() {
        console.log('activated');
    },
    deactivated() {
        console.log('deactivated');
    },
    beforeDestroy() {
        console.log('beforeDestroy');
    },
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Kick Buttowski