问题描述
我已经尝试计算在这样的组件上使用了多少 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++
如何计算一个组件上使用了多少个指令?
提前致谢:)
解决方法
count++
当前在 handler
中,它被传递给 IntersectionObserver
,因此 count
只会在相交时递增。该更新可能应该从 handler
移到 bind()
调用的根目录:
export default {
definition: {
bind: (el,binding) => {
count++
const handler = /*...*/
//...
}
}
}