【问题标题】:VUE Count how many directives are used on a componentVUE 统计一个组件上使用了多少指令
【发布时间】:2021-04-19 04:20:06
【问题描述】:

我试图计算在这样的组件上使用了多少directives。但它并没有像我预期的那样工作

这是我的指令文件

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)
    }
  }
}

这就是我在组件上调用directive 的方式

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

变量计数未存储val++

如何计算一个组件上使用了多少指令?

提前致谢:)

【问题讨论】:

  • 您似乎故意减少了所有问题。请不要。你不应该改变有答案的问题。 StackOverflow 也希望保持良好的旧 Q/A 对。如果您有特殊原因想要删除您的问题,请标记它们以引起版主注意并在此处解释原因。

标签: javascript vue.js vue-directives


【解决方案1】:

count++ 当前位于handler 中,它被传递给IntersectionObserver,因此count 只会在相交时递增。该更新可能应该从handler 移到bind() 调用的根目录:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-01-15
    • 1970-01-01
    • 2010-10-21
    • 2014-09-01
    • 1970-01-01
    • 2018-12-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多