将额外的参数传递给 IntersectionObserver?

Ste*_*n-v 5 javascript vue.js vue-component vuejs2 intersection-observer

我如何将额外的参数传递给 IntersectionObserver?我正在尝试为 Vue 创建一个延迟加载插件。它工作得很好,但我也希望能够调用提供的指令函数。

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);
            }
        });
    }
};
Run Code Online (Sandbox Code Playgroud)

这意味着在插入的函数中我将设置binding为第二个参数。

inserted(element, binding)
Run Code Online (Sandbox Code Playgroud)

我将如何传递此绑定,以便我可以在 IntersectionObserver 回调中使用它?

最后它应该看起来像这样:

<div class="col-sm-6" v-lazy="fire">
Run Code Online (Sandbox Code Playgroud)

ton*_*y19 0

您可以使用以下方式访问指令的参数binding.value

// html
<div v-lazy="0.5"></div>

// script
Vue.directive('lazy', {
  inserted(el, binding) {
    console.log(binding.value) // 0.5
  }
})
Run Code Online (Sandbox Code Playgroud)

IntersectionObserver为每个指令用法创建一个新的指令可能是有意义的。例如,您可能希望其中一个div具有与另一个不同的滚动阈值div。在inserted回调中,我将使用指令参数中指定的选项创建观察者:

const makeObserver = options => new IntersectionObserver((entries) => {
  entries.forEach((entry) => {
    console.log({entry, ratio: options.threshold})
    if (entry.intersectionRatio >= options.threshold) {
      console.log('In viewport', {entry, ratio: options.threshold});
    }
  });
}, options);

Vue.directive('lazy', {
  inserted(el, binding) {
    const options = binding.value || {}
    const observer = makeObserver(options)
    observer.observe(el)
  }
})
Run Code Online (Sandbox Code Playgroud)

然后,您可以使用该指令创建div具有不同参数的多个 s IntersectionObserver

<div style="height: 100px; background: gray" v-lazy="{root: null, threshold: 0.1}"></div>
<div style="height: 200px; background: lightgray" v-lazy="{root: null, threshold: 1}"></div>
Run Code Online (Sandbox Code Playgroud)

演示