0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Vue.jsでonScrollを特定の要素に対して実装する

Posted at

なにこれ

  1. Vue.js(筆者はnuxt.jsを使った)使ってて、特定の要素内でスクロール時に処理したい。
  2. おっ、公式ドキュメントでonScrollのサンプルあるやんけ!
  3. 動かないんだが???

という人向け

結論

カスタムディレクティブに停止してるコードをこれに変える

import Vue from 'vue'

Vue.directive('scroll', {
    inserted: function (el, binding) {
        let f = function (evt) {
            if (binding.value(evt, el)) {
                el.removeEventListener('scroll', f)
            }
        }
        el.addEventListener('scroll', f)
    }
})

公式のカスタムディレクティブの問題点

公式では以下のようなコードでイベントリスナーを追加している。

Vue.directive('scroll', {
  inserted: function (el, binding) {
    let f = function (evt) {
      if (binding.value(evt, el)) {
        window.removeEventListener('scroll', f)
      }
    }
    window.addEventListener('scroll', f)
  }
})

なんだけど、overflow-y: scrollとか使って特定の要素内スクロールを実現すると、動かない。
これはwindowとしてはscrollしてないので、イベントが発火しないからである。

Web サイト上でスクロールイベントと連動するアニメーションなど
公式の対象としては上記内容を想定しているので、当たり前と言えば当たり前なのだが、筆者がやりたいことには合致しなかった。

修正

windowではなくelを対象にしてあげればよい。

// window.removeEventListener
el.removeEventListener
// window.addEventListener
el.addEventListener

ただこれだとページ全体のスクロールイベントは発火しなくなるので、別のカスタムディレクティブを設定してあげるとよいかもしれないね。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?