LoginSignup
2
3

More than 5 years have passed since last update.

vue-routerで遷移時にスクロールアニメーションさせる

Posted at

なんとか実装できたので、メモ。

概要

やっていることは、これだけです。

  1. vue-routerで遷移をするのをbeforeEachで取得します
  2. 遷移するときにparamsにフラグを持たせます
  3. フラグを見てアニメーションスクロールします

開発環境

こんな感じです。

package.json
  "dependencies": {
    "smooth-scroll": "^12.1.5",
    "vue": "^2.5.16",
    "vue-router": "^3.0.1",
    "vuex": "^3.0.1"
  }

コードの抜粋

関係しているところだけ、まとめました。

app.js
// vue-routerを設定している箇所(とくに何もなし)
const router = new VueRouter({
  routes: routes,
})

// スクロールアニメーションのライブラリ
import SmoothScroll from 'smooth-scroll'
const scroll = new SmoothScroll ()
// スクロール位置の要素をアンカーとしてセット
const anchor = document.querySelector ('.anchor')
// ここで遷移を見まもります
router.beforeEach((to, from, next) => {
  // paramsにlinkというフラグをもたせているので判定
  if (to.params.link) {
    scroll.animateScroll (anchor)
  }
})
page.vue
<template>
  <div>
    <router-link :to="{ name: 'top', params: { link: true } }">リンク</router-link>
  </div>
</template>

ゆるぼ

やり方が分からなかったので、無理やり感があります。
もっとスマートな方法を募集です。

2
3
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
2
3