beforeDestroy vue 动态组件

sar*_*nei 2 vue.js

如何在切换组件之前添加警报消息?(beforeDestroy 在路径改变之前不起作用......)

<template>
    <keep-alive>
        <component
          :is="dynamicComponent"
        />
     </keep-alive>
</template>
Run Code Online (Sandbox Code Playgroud)

Fer*_*big 6

正如您已经发现的那样,当您保持一个组件处于活动状态时,它不会像普通组件一样抛出“ beforeDestroy”和“ created”,因为它一直处于活动状态。

因此,Vue 为此定义了其他生命周期方法:

  • activated- 这在keep-alive加载组件时被调用
  • deactivated- 这在<keep-alive>卸载组件时被调用

你像这样使用它们:

export default {
    created() {
        console.log('created');
    },
    activated() {
        console.log('activated');
    },
    deactivated() {
        console.log('deactivated');
    },
    beforeDestroy() {
        console.log('beforeDestroy');
    },
}
Run Code Online (Sandbox Code Playgroud)