我如何将额外的参数传递给 IntersectionObserver?我正在尝试为 Vue 创建一个 lazyload 插件。它像这样工作正常,但我也希望能够调用提供的指令函数。
const lazyload = {
install(Vue) {
const observer = new IntersectionObserver((entries) => {
entries.forEach((entry) => {
if (entry.intersectionRatio > 0) {
console.log('In viewport');
}
});
});
Vue.directive('lazy', {
inserted(element) {
observer.observe(element);
}
});
}
};
这意味着在插入的函数中,我会将 binding
设置为第二个参数。
inserted(element, binding)
我如何传递这个绑定(bind),以便我可以在我的 IntersectionObserver 回调中使用它?
最后它应该看起来像这样:
<div class="col-sm-6" v-lazy="fire">
最佳答案
如果您真的想将这些值作为额外参数传递,您可以使用 Function.bind
,但您必须为每个指令调用创建一个单独的 IntersectionObserver。
我会在这里推荐一个 WeakMap,并让回调检查映射以寻找正确的处理程序。像这样的东西:
const lazyload = {
install(Vue) {
const handlers = new WeakMap();
const observer = new IntersectionObserver((entries) => {
entries.forEach((entry) => {
if (entry.isIntersecting) {
console.log('In viewport');
handlers.get(entry.target)();
}
});
});
Vue.directive('lazy', {
inserted(element, binding) {
handlers.set(element, binding.value);
observer.observe(element);
}
});
}
};
(我没有使用过 Vue,所以我不确定这是否会逐字工作)
顺便说一句,我将 entry.intersectionRatio > 0
更改为 entry.isIntersecting
。这可能是一个错误,但我在 Chrome 65 中看到,当滚动速度非常慢时,您可以获得 entry.intersectionRatio === 0 && entry.isIntersecting === true
: https://jsfiddle.net/3jgm0ch7/2/
关于javascript - 将额外参数传递给 IntersectionObserver?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48262903/