[Vuejs]-How to add css code inside custom vue directive file?

0πŸ‘

The parent node is not guaranteed to exist until the inserted hook in Vue 2 or the mounted hook in Vue 3.

Switch from the bind hook to one of the above:

// MyDirective.js
export default {
  // BEFORE:
  bind(el) {
    console.log(el.parentNode) // => null ❌ 
  }

  // AFTER (Vue 2):
  inserted(el) {
    console.log(el.parentNode) // => <div> βœ…
  }

  // AFTER (Vue 3):
  mounted(el) {
    console.log(el.parentNode) // => <div> βœ…
  }
}

demo

Leave a comment