Nuxt.jsでスムーススクロールします。
前提条件
- Nuxt.jsとPugがインストールされていること
インストール
$ npm i --save vue2-smooth-scroll
使い方
touchコマンドでプラグイン用ファイルを作成する
$ touch plugins/v-smooth-scroll.js
plugins/v-smooth-scroll.js
import Vue from 'vue'
import vueSmoothScroll from 'vue2-smooth-scroll'
Vue.use(vueSmoothScroll, {
duration: 500, // スクロールにかける時間
offset: 0, // スクロール先のオフセット
updateHistory: true // #ハッシュを適用するか
})
nuxt.config.jsでプラグインを読み込む
nuxt.config.js
module.exports = {
plugins: [
{ src: '~/plugins/v-smooth-scroll', mode: 'client' }
]
}
aタグにv-smooth-scrollと書くと、hrefで指定した要素までスムーススクロールする
pages/test.vue
<template lang="pug">
.test
a(href="#test" v-smooth-scroll) anchor
#test test
</template>
下のようにオブジェクトを渡すと、このタグ単一で設定を変更することが出来る
a(href="#test" v-smooth-scroll="{ duration: 1000, offset: -50 }") anchor
参考文献
この記事は以下の情報を参考にして執筆しました。