LoginSignup
6
4

More than 3 years have passed since last update.

Waypoints を jQuery から Vue.js に移植した

Last updated at Posted at 2019-05-24

// この記事は、 note に投稿した記事の再掲です。

「要素が表示領域に入ったらクラスを付与」みたいな実装をするのにものすごくお世話になっている Waypoints
いままでは jQuery を使って実装していましたが、まんをじして Vue.js に移植しました。

Vue.js との併用なので、利用している Waypoints ライブラリは No Framework ってやつです。

コード全文:
https://github.com/incolorsnet/note/blob/master/docs/vue-and-waypoints/index.html

動作サンプル:
https://incolorsnet.github.io/note/vue-and-waypoints/

Vue.js + Waypoints.js with GRAPEVINE

実装してみる

Waypoints は CDN からも提供されています。
<head></head> 内 もしくは、<body></body> 内の一番下に入れるとよいです。

<script src="https://cdnjs.cloudflare.com/ajax/libs/waypoints/4.0.1/noframework.waypoints.js"></script>

jQuery:

(function($){
  $(document).ready(function(){
    $('.fade_in').waypoint(function(){
      $(this.element).addClass('visible');
    }, {
      offset: '80%'
    });
  });
});

Vue.js:

const app = new Vue({
  el: '#el',

  mounted () {
    this.waypoint()
  },

  methods: {
    waypoint () {
      let elem = this.$el.querySelectorAll('.fade_in')

      elem.forEach(x => {
        this.waypoint = new window.Waypoint({
          element: x,
          handler: () => {
            x.classList.add('visible')
          },
          offset: '80%',
         })
      })

    },
  },
  beforeDestroy: function () {
    this.waypoint.destroy()
  }
})

forEach 文の書き方について、鹿野先生にご助言をいただいてとってもすっきり書くことができました。勉強になった〜〜!ありがとうございます…🙏

おまけ

クライアントワークもプライベートな制作も Waypoints を多用しています。なぜならフワッと表示させたら大体オッケーだと思っているからです。

のくら - スーツとモブ顔を愛してやまない漫画家|Suit is Good.
https://nokura.me

▲フワッとさせたので大体オッケーだと思っている運用サイトです。(このウェブサイトはまだ jQuery に依存中)

6
4
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
6
4