VUE Count how many directives are used on a component

112 Views Asked by At

I've tried to count how many directives are used on a component like this. But it does not work as I expected

this is my directive file

import ahoy from "ahoy.js"

let count = 0

export default {
  id: "bar",
  definition: {
    bind: (el, binding) => {
      const handler = (entries, observer) => {
        count++
        console.log(count)
        if (entries[0].isIntersecting) {
          setTimeout(() => {
            ahoy.track("impression", {
              ...(typeof binding.value === "object"
                ? { ...binding.value }
                : { value: binding.value }),

              page: document.title,
              path: window.location.pathname.replace(/^\/en\//g, "/"),
              class: el.classList.value
            })

            observer.unobserve(entries[0].target)
          }, 100)
        }
      }

      const createIntersection = new IntersectionObserver(handler, { rootMargin: "-45% 0%" })
      createIntersection.observe(el)
    }
  }
}

and this is how I call directive on my component

ReviewCard(
  v-bar="createIntersection(foo)"
)

variable count not stored val++

how can I count how many directives are used on a component?

Thanks in advance :)

1

There are 1 best solutions below

0
On BEST ANSWER

count++ is currently in handler, which is passed to the IntersectionObserver, so count would only be incremented upon an intersection. That update should probably be moved outside of handler to the root of the bind() call:

export default {
  definition: {
    bind: (el, binding) => {
      count++

      const handler = /*...*/
      //...
    }
  }
}