合同会社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>