Where do custom directives belong?

wcjr
3
wcjr
commented a year ago

I couldn't find anything in the guide about a best practice on this. It seems a custom directive could be a plain old javascript file with the Vue.directive(...) syntax but I don't see a clear winner for its directory or is the best practice to simply put the registration in the default.vue layout?

Just wanting to use this in my project:

// Register a global custom directive called `v-focus`
Vue.directive('focus', {
  // When the bound element is inserted into the DOM...
  inserted: function (el) {
    // Focus the element
    el.focus()
  }
})

Thanks!

1
paulgv
3.6k
paulgv
commented a year ago

I'd register directives in a plugin:

plugins/
├── directives.js
// nuxt.config.js
{
  plugins: [
    '~/plugins/directives.js'
  ]
}
1
wcjr
3
wcjr
commented a year ago

Thanks @paulgv , I was considering that but there's a statement in https://nuxtjs.org/guide/plugins about these being run before the instantiating the root Vue application…do you think directives loaded before will still be recognized once the root Vue app is instantiated?

0
wcjr
3
wcjr
commented a year ago

I did what you suggested, no problems with what I was curious about with the root Vue instantiation. @paulgv, do you think it would be worth a little statement in the guide (https://nuxtjs.org/guide/directory-structure) or README's about what to do with directives?

0
paulgv
3.6k
paulgv
commented a year ago

It would be nice to have some more examples on what you can do in plugins (register mixins, filters, directives, etc.) for sure :)

0
wcjr
3
wcjr
commented a year ago

oh good, I'm glad you think that. What can I/we do to ensure something like this is added?

0
paulgv
3.6k
paulgv
commented a year ago

The best way would be to fork https://github.com/nuxt/docs and add your examples to the plugins guide, then you can submit a PR to the main repo.

0
wcjr
3
wcjr
commented a year ago

ok @paulgv , that makes sense and it looks like running it locally isn't difficult. I'll put this on my list to do.

0
wcjr
3
wcjr
commented a year ago

hey @paulgv , I've started running into issues with the spa aspects of nuxt and am going to have to abandon nuxt for now. Hopefully simply having this note here will help others in the future. Thanks!

You can close the issue if you don't have anyone you could assign this to.

0
Informations
QuestionResolved
#c2708 - Created a year ago