LoginSignup
12
12

More than 5 years have passed since last update.

vue-routerのhistoryモードでハッシュ付きリンクのスクロール位置を指定する

Last updated at Posted at 2018-01-07

普段のサイトではよく見かける、「リンク先ページの指定のセクションまでスクロールさせて表示する」実装をVue+vue-routerで実装した話です。

最終的にはscrollBehaviorのリファレンスに載っていたのですが、たどり着くのに時間がかかったので、共有がてらまとめておきます。

scrollBehavior option について

vue-router には、 scrollBehavior というその名の通りスクロール位置の振る舞い(初期位置)について設定できるoptionがあります。
それの返し値として、以下の3種類が設定できます。

  1. { x: number, y: number }
  2. { selector: string }
  3. { selector: string, offset? : { x: number, y: number }} (2.6.0 以降においてだけ offset はサポート)

今回はヘッダーなどのoffset値は気にしなくて良いので、1の指定方法(+ハッシュがない時用に2の指定方法)を使用します。

実装したこと

実際のコードは↓のような感じです。
scrollBehavior内で location.hash をみるだけです。

Vue.use(VueRouter);

const config = {
  routes,
  mode: 'history',
  scrollBehavior(to, from, savedPosition) {
    // ハッシュがある時にはその地点へとスクロールする
    const selector = location.hash
    return selector ? { selector } : { x: 0, y: 0 }
  }
}

export default new VueRouter(config);

あとは通常のサイト制作と同じように、リンクの設定とid指定だけで動作しました。

<router-link to="hoge#pos1">hogeのpos1へ</router-link>

おわりに

とりあえず最低限の挙動をするようになったので十分です。
今回はスムーズスクロールなどは実装していませんが、 scrollBehaivor optionをつかえばそちらの方も比較的簡単に実装できるのではないかと思います。

12
12
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
12
12