学习优先度:★★★★★

难易度:★★★☆☆

生命周期钩子提供了在组件生命周期的特定阶段执行代码的方法。

在 Vue.js 中,生命周期钩子是允许您在组件生命周期的特定阶段(如创建、加载、更新或销毁时)添加代码的方法。

【代码示例】

<template>
  <div>
    <p>{{ message }}</p>
 </div>
</template>
<script>
export default {
 data() {
  return {
   message: "Hello, Vue!"
  };
 },
 created() {
  console.log("Component is created!");
 },
 mounted() {
  console.log("Component is mounted!");
 },
 updated() {
  console.log("Component is updated!");
 },
 destroyed() {
  console.log("Component is destroyed!");
 }
};
</script>

【执行结果】

textComponent is created!
Component is mounted!

created(): 该钩子在实例创建后调用。在此阶段,组件的数据是被动的,但模板尚未渲染。

mounted(): 此钩子在组件安装到 DOM 后调用。这是执行依赖于 DOM 的操作的好地方。

updated(): 该钩子在组件的数据发生变化且 DOM 更新后被调用。您可以在组件重新渲染后使用它来执行操作。

destroyed(): 该钩子在组件销毁时被调用。您可以用它来清理定时器或事件监听器等资源。

生命周期钩子是功能强大的工具,可让您在组件存在的不同阶段控制其行为。

【补充】

Vue.js 总共提供了 12 个生命周期钩子,包括 beforeCreate、created、beforeMount、mounted、beforeUpdate、updated、activated、deactivated、beforeDestroy 和 destroyed。每个钩子都有特定的用途,可用于在组件的生命周期中执行不同的操作。