LoginSignup
5
5

More than 5 years have passed since last update.

jQueryを使わずにスムーズなスクロールを実装

Last updated at Posted at 2017-07-30

合同会社kumanoteのTanakaです。
最近vueを使ってクライアントサイドを構築することが増えてきました。
今回は、よくある、アンカーリンクをクリックした時にスムーズにスクロールするやり方を
jQueryを使わずに実装するTipsをご紹介します。

smoothScrollというライブラリがMITライセンスで作られていますので
こちらを利用しました。

install

$ npm install --save smoothscroll

npmを使わなくてもsmoothscroll.min.jsをローカルにもってきて参照しても使えるはずです。

使い方

汎用的な使い方

// たとえば、#hogeというid属性の要素に飛びたい時
import smoothScroll from 'smoothscroll'             // ライブラリ呼び出し
const target = window.document.querySelector('#hoge') // hogeのnodeを取得
smoothScroll(target)                                // スクロール実行

これだけです!便利ですね。

vue-routerの場合

現在のpathと比較して、同一ページであれば、スクロールする実装が有用です。

<template>
  <a href="/#hoge" @click="move('/', '#hoge')"><span>hoge</span></a>
</template>
<script>
import smoothScroll from 'smoothscroll'
export default {
  methods: {
    move: function (path, selector) {
      if (path === this.$route.path) {
        const target = window.document.querySelector(selector)
        smoothScroll(target)
      }
    }
  }
}
</script>
5
5
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
5
5