<[object Object] defer="true" src="https://static.cloudflareinsights.com/beacon.min.js" token="0a1dcfae6c4348e2aa2d13c20d9fe61d">

# Custom Directives

Usually one should let the framework do the communication and manipulation of the DOM without explicitly intervening.

But there are times when you would want a little bit of control at that low level, so Vue has your back in that scenario.

TIP

Official docs here

To create a directive, you could register it globally by doing the following:

Vue.directive( 'directiveName',
    { /* configuration object goes here */ }
)
1
2
3

Or if you wanted to do it locally, there is a directives option in the instance (or component) configuration object:

new Vue({
    ...
    directives: {
        directiveName: {
            /* configuration object goes here  */
        }
    }
    ...
})
1
2
3
4
5
6
7
8
9

There are hook functions you can provide in the configuration object for a directive, namely:

    bind()
    inserted()
    update()
    componentUpdated()
    unbind()
1
2
3
4
5

Each one runs at a different point in time, depending on the state of your directive in the DOM and related to the parent (containing) VNode's own state.

Also, they receive a list of hook arguments that will give you further access to certain data that describes the directive even more.

I'll just give you an example so you get an idea of what you can do with directives.

Keep in mind though, that most of the time you want to create components and these directives are intended to give you access to lower level DOM operations.

See the Pen 09. Custom directives by @ackzell on CodePen.

Last Updated: 9/15/2020, 12:54:52 AM