Custom Directive in nuxt js

Tested in nuxt-edge ( its nuxt 2.0 that will be out in this or next month, but its pretty stable as it is).

nuxt.config.js

  render: {
    bundleRenderer: {
      directives: {
        cww: function (vnode, dir) {
          const style = vnode.data.style || (vnode.data.style = {})
          style.backgroundColor = '#ff0016'
        }
      }
    }
  }

page.vue

<div v-cww>X</div>

Resulting html from server:

<div style="background-color:#ff0016;">X</div>

If you want use custom directives in Nuxt you can do the following:

  • Create a file inside plugins folder, for example, directives.js
  • In nuxt.config.js add something like plugins: ['~/plugins/directives.js']

In your new file add your custom directive like this:

import Vue from 'vue'

Vue.directive('focus', {
  inserted: (el) => {
    el.focus()
  }
})

How To Create A Directive


You can make directives run on the client by adding the .client.js extension to your directives file. This works for SSR and static rendering.

// plugins/directive.client.js

import Vue from 'vue'

Vue.directive('log-inner-text', {
  inserted: el => {
    console.log(el.innerText)
  }
})

How To Insert Directives

In your nuxt.config.js file add it as a plugin like this.

plugins: [
  '~/plugins/directive.client.js'
]

Don't forget to save your directive in the plugins folder.


How To Use A Directive

<div v-log-inner-text>Hello</div>

Console logs

> "Hello"

I have written a medium article that goes a lot more in-depth on how this works. It shows you how to make a directive that makes an element animate into view on scroll: Nuxt - Creating Custom Directives For Static & SSR Sites