在 Vue.js 中,钩子函数(也叫生命周期钩子)是指在组件生命周期内自动调用的一些特定函数。Vue 提供了一系列的生命周期钩子函数,让开发者可以在组件的不同阶段执行自定义的代码。

常见的 Vue 生命周期钩子

1. beforeCreate

  • 触发时机:实例被创建之后,数据观测和事件/侦听器设置之前。
  • 用途:此时,数据和事件还未初始化。
beforeCreate() {
  console.log('beforeCreate');
}

2. created

  • 触发时机:实例创建完成后,数据观测和事件/侦听器设置完成,挂载开始之前。
  • 用途:适合进行一些数据初始化操作。
created() {
  console.log('created');
}

3. beforeMount

  • 触发时机:模板首次挂载到 DOM 之前。
  • 用途:在这时可以访问 el 和模板,但实际的 DOM 还未生成。
beforeMount() {
  console.log('beforeMount');
}

4. mounted

  • 触发时机:实例挂载后,模板已经渲染到 DOM 上。
  • 用途:适合执行需要 DOM 元素的操作,例如与第三方库的集成
mounted() {
  console.log('mounted');
}

5. beforeUpdate

  • 触发时机:数据更新时,DOM 更新之前。
  • 用途:适合在数据变化时进行某些操作(例如记录日志或优化某些 UI 操作)
beforeUpdate() {
  console.log('beforeUpdate');
}

6. updated

  • 触发时机:数据更新完成,DOM 重新渲染之后。
  • 用途:适合在视图更新后进行 DOM 操作或其他处理。
updated() {
  console.log('updated');
}

7. beforeDestroy

  • 触发时机:实例销毁之前,组件的监听器和子组件将被销毁。
  • 用途:适合进行清理操作,例如移除事件监听器、定时器等
beforeDestroy() {
  console.log('beforeDestroy');
}

8. destroyed

  • 触发时机:实例销毁之后,所有的事件监听器和子组件都已经销毁。
  • 用途:可以进行销毁后的清理。
destroyed() {
  console.log('destroyed');
}

9. activated

  • 触发时机:当组件被激活时(用于 <keep-alive> 包裹的组件)。
  • 用途:当组件被缓存并重新激活时触发。
activated() {
  console.log('activated');
}

10. deactivated

  • 触发时机:当组件被缓存并且停用时(用于 <keep-alive> 包裹的组件)。
  • 用途:当组件被缓存并且停用时触发。
deactivated() {
  console.log('deactivated');
}

钩子函数的执行顺序

  1. beforeCreate
  2. created
  3. beforeMount
  4. mounted
  5. beforeUpdate
  6. updated
  7. beforeDestroy
  8. destroyed

示例:完整生命周期钩子

<template>
  <div>
    <h1>{{ message }}</h1>
  </div>
</template>

<script>
export default {
  data() {
    return {
      message: "Hello, Vue!"
    };
  },
  beforeCreate() {
    console.log("beforeCreate");
  },
  created() {
    console.log("created");
  },
  beforeMount() {
    console.log("beforeMount");
  },
  mounted() {
    console.log("mounted");
  },
  beforeUpdate() {
    console.log("beforeUpdate");
  },
  updated() {
    console.log("updated");
  },
  beforeDestroy() {
    console.log("beforeDestroy");
  },
  destroyed() {
    console.log("destroyed");
  }
};
</script>

使用场景

  • beforeCreate 和 created:用来处理数据初始化,通常用在组件初始化时。
  • beforeMount 和 mounted:适用于与 DOM 相关的操作,如初始化 DOM 插件或做动画处理。
  • beforeUpdate 和 updated:适合在数据变化时或视图更新时执行操作。
  • beforeDestroy 和 destroyed:清理资源,如定时器、事件监听器等。

Vue 的生命周期钩子函数是开发中非常重要的部分,通过它们可以在不同的生命周期阶段插入自定义逻辑。