Introduction

Let explore Vue’s lifecycle hooks which include activated, deactivated, errorCaptured, renderTracked, and renderTriggered in this article. Vue 3 just release recently and updated some cool features for an example renderTracked and renderTriggered lifecycle hooks. The other lifecycle hooks are explained here.

activated and deactivated

activated and deactivated lifecycle hooks will be invoked accordingly when a component is wrapped by a dynamic component — keep-alive. This dynamic component is useful if want to preserve/maintain the previous state’s when switching the tab or navigate to another page.

  • activated hook shows that the dynamic component **e.g. Home component **is active on the web page.
  • The deactivated hook is called when load another dynamic component and the dynamic component e.g. Home component is not active. However, their state is not changing when the dynamic component is not active.

Demo Scenario : Tab Component created and wrapped with the keep-alive.

 <script>
    const app = Vue.createApp({
      data() {
        return {
          selectedComponent: "tab-home",
        };
      },
    });

    app.component("tab-home", {
      template: `<div class="demo-tab">Home component</div>`,
      activated() {
        console.log("tab-home activated");
      },
      deactivated() {
        console.log("tab-home deactivated");
      },
    });
    app.component("tab-info", {
      template: `<div><br>
        <input v-model="name" placeholder="Name" />
        <p>My Name is: {{ name }}</p>
        </div>`,
      data() {
        return {
          name: "",
        };
      },
      activated() {
        console.log("tab-info activated");
      },
      deactivated() {
        console.log("tab-info deactivated");
      },
    });
    app.component("tab-about", {
      template: `<div class="demo-tab">Archive component</div>`,
      activated() {
        console.log("tab-about activated");
      },
      deactivated() {
        console.log("tab-about deactivated");
      },
    });

    app.mount("#dynamic-component-demo");
  </script>

activated and deactivated hooks (JavaScript Code)

Image for post

activated and deactivated for each component

errorCaptured

errorCaptured only triggered by any descendent component is captured. There is another function for the global error handler which is errorHandler. But this function does not capture event handler error. It will capture during component render function and watchers. For more information, you may read from here.

The errorCaptured hook receives 3 parameters:

  • an **error **that displays messages.
  • a **component **that will output a proxy object.
  • **info **that will tell you what kind of error is e.g. render function or native event handler.

#vue #javascript #web-development #programming #developer

How to use Vue Lifecycle Hooks (Part 2)
3.75 GEEK