# Vue 中监听组件生命周期

# 1.内部监听生命周期函数

Vue 组件中,可以用 $on ,$once 去监听所有的生命周期钩子函数,如监听组件的 beforeDestroy 钩子函数可以写成:

export default {
  mounted() {
    // TODO
    this.$once("hook:beforeDestroy", () => {
      //TODO
    });
  },
};

# 2.外部监听生命周期函数

通过 @hook:updated 监听组件的 updated 生命钩子函数
组件的所有生命周期钩子都可以通过 @hook:hookName 来监听触发

<template>
  <custom-select @hook:updated="handleFunc" />
</template>
<script>
  import CustomSelect from "@/components/CustomSelect";
  export default {
    components: {
      CustomSelect,
    },
    methods: {
      handleFunc() {
        //TODO
      },
    },
  };
</script>
最后更新时间: 2022-07-07 15:25