Custom instructions (defineDirective) and hook functions (created, mounted, updated, unmounted) in Vue3

Directory

  • Custom instructions
    • Example 1
    • Example 2
  • hook function
  • The relationship between custom instructions and hook functions

This article mainly introduces the use of custom instructions and hook functions in Vue3 and the relationship between them.

Custom directive

In Vue3, custom directives are a way to extend Vue’s template syntax. Custom directives are actually a special attribute that can be applied via the v- prefix.

Custom instructions can add behaviors to elements, such as focusing the input box, scrolling to a specified position, lazy loading, etc. At the same time, you can perform some logic when binding and unbinding the instructions, and you can also receive parameters and modifiers for more flexible processing. control.

In Vue3, custom directives are defined through the directive function and are exposed as return values in the setup function so they can be used in templates.

Example 1

For example, here is an example of using custom instructions to focus the input box in Vue3:

<template>
  <input v-focus />
</template>

<script>
import {<!-- --> directive } from 'vue';

const focus = directive((el) => {<!-- -->
  el.focus();
});

export default {<!-- -->
  directives: {<!-- -->
    focus
  }
}
</script>

In the above code, we define a custom directive named focus and register it in the component’s directives option, using in the template v-focus Apply this command to realize the input box focusing function.

Example 2

The following is an example of using a custom directive function. Suppose there is a requirement that only numbers can be entered in the input box, and input of other characters is invalid. We can achieve this function through custom instructions.

<template>
  <div>
    <input v-number-only type="text" v-model="value" />
  </div>
</template>

<script>
import {<!-- --> defineDirective } from 'vue'

export default {<!-- -->
  setup() {<!-- -->
    const value = ref('')

    return {<!-- -->
      value,
    }
  },
  directives: {<!-- -->
    'number-only': defineDirective((el) => {<!-- -->
      el.addEventListener('input', (e) => {<!-- -->
        const value = e.target.value
        e.target.value = value.replace(/\D/g, '')
      })
    })
  }
}
</script>

In this example, we define a custom directive v-number-only, use the defineDirective method to create a hook function el, and This hook function listens to the input event of the input box and replaces non-numeric characters with null characters when the event is triggered. Use this command in the template to realize the function of inputting only numbers.

Hook function

In Vue3, hook functions are functions used to perform specific operations during the component life cycle. Similar to the life cycle hooks in Vue2, Vue3 also provides some specific hook functions that can perform some logic in different life cycle stages of the component.

In Vue3, the component’s hook function can be placed in the setup function and implemented by directly defining the function. Commonly used hook functions include:

  • beforeCreate: Executed before the component is instantiated.
  • created: Executed after the component is instantiated, but data observations and event/life cycle hooks are not mounted.
  • beforeMount: Executed before the component is mounted.
  • mounted: Executed after the component is mounted.
  • beforeUpdate: Executed before the component is updated.
  • updated: Executed after the component is updated.
  • beforeUnmount: Executed before the component is unmounted.
  • unmounted: Executed after the component is unmounted.

For example, here is an example of using a hook function in Vue3 to automatically switch the page title:

<template>
  <div>
    <h1>{<!-- -->{ title }}</h1>
    <button @click="changeTitle">Change Title</button>
  </div>
</template>

<script>
import {<!-- --> onMounted, onBeforeUnmount, ref } from 'vue';

export default {<!-- -->
  setup() {<!-- -->
    const title = ref('Welcome to the Page!');
    
    const changeTitle = () => {<!-- -->
      title.value = 'New Title';
    };
    
    const updatePageTitle = (newTitle) => {<!-- -->
      document.title = newTitle;
    };
    
    onMounted(() => {<!-- -->
      updatePageTitle(title.value);
    });
    
    onBeforeUnmount(() => {<!-- -->
      updatePageTitle('Goodbye!');
    });
    
    return {<!-- -->
      title,
      changeTitle
    };
  }
}
</script>

In the above code, we use the onMounted and onBeforeUnmount hook functions to update the title of the page when the component is mounted and unmounted. The title and changeTitle variables are defined in the setup function, and the onMounted function calls when the component is mounted. The updatePageTitle function updates the page title to the component title. The onBeforeUnmount function calls the updatePageTitle function to update the page title to “Goodbye!” when the component is unmounted.

The relationship between custom instructions and hook functions

In Vue3, custom directives and hook functions are closely related.

Custom directives are a way to directly manipulate the DOM in the template. You can define directives with specific behaviors in the component and use them in the template to implement certain functions.

Hook functions are functions that are executed during the life cycle and can perform specific operations at different stages of the component. Custom directives can be defined and used in hook functions.

The way custom directives are implemented is a little different than in Vue2. In Vue3, custom directives no longer have bind and update hook functions.

Regarding the relationship between custom instructions and hook functions, it can be simply understood as:

  • A custom instruction is an object that contains a series of hook functions (life cycle functions);
  • Hook functions are part of custom instructions. They are triggered during the life cycle of the instruction to implement related functions.

For example, you can create a custom directive named myDirective, with beforeMount and mounted hook functions. To reference this directive in a template you can write:

<div v-myDirective>Customized directive content</div>

To implement this instruction in code you can write:

const myDirective = {<!-- -->
  beforeMount(el, binding, vnode, prevVnode) {<!-- -->
    // Called before the parent component of the bound element is mounted
  },
  mounted(el, binding, vnode, prevVnode) {<!-- -->
    // Called after the parent component of the bound element is mounted
  }
}

const app = createApp({<!-- -->})
app.directive('myDirective', myDirective)

In the above example, myDirective is the name of the custom directive, and beforeMount and mounted are the hook functions of the directive. createApp({}) is used to create a Vue3 instance, and app.directive('myDirective', myDirective) is used to register custom directives into the instance.