Detailed explanation of the life cycle of Vue in Vue learning

overview

Post Vue's official website here: Vue's life cycle hook

The life cycle of a Vue component can be divided into the following eight phases:

  1. beforeCreate: The component instance has just been created, the properties and methods have not been initialized, and data, props, computed and other data cannot be accessed.

  2. created: The component instance is created, the properties and methods have been initialized, but the DOM has not been rendered yet. You can access data, props, computed and other data, and perform some initialization operations.

  3. beforeMount: The component will be mounted on the page, and the DOM has not been rendered yet.

  4. mounted: The component has been mounted on the page, and the DOM has been rendered at this time, and some DOM operations and data requests can be performed.

  5. beforeUpdate: Called before the component is updated, and the DOM has not been updated at this time.

  6. updated: It is called after the component is updated. At this time, the DOM has been updated, and some DOM operations and data requests can be performed.

  7. beforeDestroy: The component is about to be destroyed. At this time, the component can still access data, props, computed and other data, and can perform some cleaning operations.

  8. destroyed: The component has been destroyed. At this time, the component cannot access data, props, computed and other data.

At each life cycle stage, Vue provides corresponding hook functions, and programmers can write code in these hook functions to handle corresponding operations. At the same time, at each life cycle stage, programmers can obtain and manipulate corresponding data and methods by accessing component instances.

Explain in detail the application of each lifecycle

The life cycle of Vue components can be divided into 8 stages, and programmers can perform some specific operations in each stage. Here is a detailed introduction to the specific instructions of each stage, the APIs that can be obtained, and the things that programmers can do.

beforeCreate (before creation)

beforeCreate (before creation) is called before the component is instantiated. At this time, the programmer can get the configuration object (options) of the component, but cannot access the data and methods of the component. At this point the component has not been initialized yet, so there are no DOM elements. At this stage, programmers can do some initialization work, such as loading external data, initializing events, and other operations. Available APIs:

  • this.$options: Access the component's configuration object.

  • Things programmers can do:

    • Load external data.

    • Init event.

created (after creation)

created (after creation) is called immediately after the component is instantiated. At this time, the programmer can access the data and methods of the component, but cannot access the DOM elements. At this point the component has not been mounted on the page. At this stage, programmers can do some component initialization work, such as operating data, accessing servers, and other operations. Available APIs:

  • this: Access the data and methods of the component.

  • Things programmers can do:

    • Operate on the data.

    • Access the server.

beforeMount (before mounting)

beforeMount (before mounting) is called before the component is mounted on the page. At this time, the programmer can access the data and methods of the component, as well as the DOM elements. At this stage, programmers can perform some initialization operations on components, such as modifying the style of DOM elements, adding event listeners, and so on. Available APIs:

  • this: Access the data and methods of the component.

  • this.$el: Accesses the component's DOM element.

  • Things programmers can do:

    • Modify the style of a DOM element.

    • Add event listeners.

mounted (after mounting)

mounted (after mounting) is called after the component is mounted on the page, at this time, the programmer can access the data and methods of the component, as well as the DOM elements. At this stage, programmers can perform some operations that require access to DOM elements, such as obtaining the width and height of DOM elements, adding third-party libraries, and so on. Available APIs:

  • this: Access the data and methods of the component.

  • this.$el: Accesses the component's DOM element.

  • Things programmers can do:

    • Get the width and height of a DOM element.

    • Add third-party libraries.

beforeUpdate (before update)

beforeUpdate (before update) is called before the component is updated, at this time the programmer can access the data and methods of the component, as well as the DOM elements. At this stage, the programmer can perform some data preparation work, such as calculating the data that needs to be updated, clearing some data, and so on. Available APIs:

  • this: Access the data and methods of the component.

  • this.$el: Accesses the component's DOM element.

  • Things programmers can do:

    • Calculate the data that needs to be updated.

    • Clear some data.

updated (updated)

updated (updated) Called after the component is updated, at this time the programmer can access the data and methods of the component, as well as the DOM elements. At this stage, programmers can perform some DOM operations, such as modifying the style of DOM elements, adding event listeners, and so on. Available APIs:

  • this: Access the data and methods of the component.

  • this.$el: Accesses the component's DOM element.

  • Things programmers can do:

    • Modify the style of a DOM element.

    • Add event listeners.

Note : update events ( beforeUpdateand updated) can be triggered repeatedly

Get the dom elements before and after the update

<template>
  <div>
    <h1>{
   
   { message }}</h1>
    <button @click="changeMessage">修改消息</button>
  </div>
</template>
<script>
export default {
  data() {
    return {
      message: 'Hello, Vue!'
    }
  },
  updated() {
    console.log('组件更新完成');
    const el = this.$el; // 获取更新后的 DOM 元素
    const instance = this; // 获取更新后的组件实例
    // 可以在这里做一些操作,例如获取更新后的计算属性值、操作子组件等
  },
  methods: {
    changeMessage() {
      this.message = 'Hello, World!';
    }
  }
}
</script>

In updatedthe hook function, we can getthis.$el the updated DOM element through and the updated component instance through , and do some operations here, such as getting the updated computed property value, operating subcomponents, etc. thisIt should be noted that updatedthe hook function will only be called after the component's VNode is updated, so before that, we cannot get the updated information.

Similar method for updated dom elements:$nextTick

The next T ick method is often used to perform some action after the DOM has been updated, such as getting the updated DOM element or setting focus after the update. The nextTick method is often used to perform some action after the DOM has been updated, such as getting the updated DOM element or setting focus after the update.The nextTick method is often used to perform some operations after the DOM is updated, such as getting the updated DOM element or setting the focus after the update . The nextTick method is executed asynchronously, so the callback function is guaranteed to be executed after the DOM update is complete.

<template>
  <div>
    <h1 ref="title">{
   
   { message }}</h1>
    <button @click="changeMessage">修改消息</button>
  </div>
</template>
<script>
export default {
  data() {
    return {
      message: 'Hello, Vue!'
    }
  },
  methods: {
    changeMessage() {
      this.message = 'Hello, World!';
      this.$nextTick(() => {
        console.log(this.$refs.title.innerText); // "Hello, World!"
        this.$refs.title.focus(); // 设置标题元素的焦点
      });
    }
  }
}
</script>

In the above code, changeMessagewe modify messagethe value in the method, and get the updated title element and set its focus after the DOM update is completed through $nextTickthe method .

Similar method for updated dom elements:$watch

$watchMethods are often used to listen for changes in data and perform certain operations when the data changes.

<template>
  <div>
    <h1>{
   
   { message }}</h1>
    <button @click="changeMessage">修改消息</button>
  </div>
</template>
<script>
export default {
  data() {
    return {
      message: 'Hello, Vue!'
    }
  },
  watch: {
    message(newVal, oldVal) {
      console.log(`message 从 ${oldVal} 变为 ${newVal}`);
    }
  },
  methods: {
    changeMessage() {
      this.message = 'Hello, World!';
    }
  }
}
</script>

In the above code, $watchwe listened to messagethe changes through the method, and printed the values ​​before and after the change when the message changed.

beforeDestroy (before destruction)

beforeDestroy (before destruction) is called before the component instance is destroyed. At this time, the programmer can access the data and methods of the component, as well as the DOM elements. At this stage, programmers can do some cleanup work, such as canceling event listeners, clearing timers, and so on. Available APIs:

  • this: Access the data and methods of the component.

  • this.$el: Accesses the component's DOM element. Things programmers can do:

  • Cancel the event listener.

  • Clear timer.

destroyed (after destruction)

destroyed (after destruction) Called after the component instance is destroyed, at this time, the programmer cannot access the data and methods of the component, nor can he access the DOM elements. At this stage, programmers can perform some cleanup tasks, such as freeing memory and canceling network requests.

  • Available APIs: None

  • Things programmers can do:

    • free memory.

    • Cancel a network request.

code example

<template>
  <div>
    <h1>{
   
   { message }}</h1>
    <button @click="changeMessage">修改消息</button>
  </div>
</template>
<script>
export default {
  data() {
    return {
      message: 'Hello, Vue!'
    }
  },
  beforeCreate() {
    console.log('组件被创建前');
  },
  created() {
    console.log('组件被创建后');
  },
  beforeMount() {
    console.log('组件被挂载前');
  },
  mounted() {
    console.log('组件被挂载后');
  },
  beforeUpdate() {
    console.log('组件更新前');
  },
  updated() {
    console.log('组件更新后');
  },
  beforeDestroy() {
    console.log('组件销毁前');
  },
  destroyed() {
    console.log('组件销毁后');
  },
  methods: {
    changeMessage() {
      this.message = 'Hello, World!';
    }
  }
}
</script>

In the code above, we define a simple component that contains a button and a message. In the component's life cycle, we console.log()output . Additionally, we define a changeMessage()method for modifying the message. In this method, we change the data of the component and update the message in real time on the page.

Guess you like

Origin blog.csdn.net/qq_45074341/article/details/129682821