Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom Directive in nuxt js

is there a way how to write a custom directive in nuxt js, which will work for ssr and also for frontend (or even for ssr only)?

I tried it like in following documentation: https://nuxtjs.org/api/configuration-render#bundleRenderer

so I added this code:

  module.exports = {
      render: {
        bundleRenderer: {
          directives: {
            custom1: function (el, dir) {
              // something ...
            }
          }
        }
      }
    }

to nuxt.config.js

then I use it in template as:

<component v-custom1></component>

but it doesn't work, it just throw the frontend error

[Vue warn]: Failed to resolve directive: custom1

And it doesn't seem to be working even on server side.

Thanks for any advice.

like image 732
Martin Rázus Avatar asked Jul 17 '18 15:07

Martin Rázus


2 Answers

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()
  }
})
like image 177
AitorDB Avatar answered Sep 23 '22 08:09

AitorDB


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

like image 38
Fletcher Rippon Avatar answered Sep 22 '22 08:09

Fletcher Rippon