In general, if you need to perform low-level operations on DOM elements, you will need to use custom directives. In VUE3 we can customize local and global directives. Let’s customize a v-focus automatic focus command.

1. Local instructions

Local directives can only be used in the current component. So how do you define a local directive? We name a directive named Focus in the Directives option, Focus has many life cycles (created, bdforeMount, Mounted, beforeUpdate, updated, beforeUnmount, unmounted). Get focus with el.focus(). The code is as follows:

export default {
  directives: {
    focus: {
      mounted(el, bindings, vnode, preVnode) {
        el.focus()
      }
    }
  }
};
Copy the code

Thus, we simply add v-focus to the input tag to automatically get focus when mounting. The code is as follows:

<input type="text" v-focus />
Copy the code

2. Global instructions

If we want to define a global directive, in vue’s main.js function, we create the instance with const app = createApp(app), and customize the directive with app.directive(). App.directive (‘name’,{}) takes two parameters, the first is the directive name and the second is the action. Example code is as follows:

import { createApp } from 'vue'
import App from './03. Custom directive/app.vue '

const app = createApp(App)
app.directive('focus', {
  mounted(el, bindings, vnode, preVnode) {
    el.focus()
  }
})
app.mount('#app')
Copy the code

This allows us to use the V-focus directive on any component to get focus.