0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

[Vue]ページ遷移時にページを画面のトップに戻したい

Posted at

概要

Vue Routerでページ遷移する時、前のページのスクロール位置のまま遷移してしまうので画面が中途半端な位置になってしまいます。

ページ遷移した時に画面トップに戻る処理を実装できるのがscrollBehavior関数です。

実装

.js
const router = new VueRouter({
  mode: 'history',
  routes: [
    {
      path: '/',
      name: 'home',
      component: HomeComponent,
      props: true,
      meta: {isPublic: true},
      children: [
        {
          path: '/trend',
          name: 'trend',
          components: {
            trend: TrendTimeline,
          },
          props: true,
          meta: {isPublic: true},
        },
        {
          path: '/item',
          name: 'item',
          components: {
            item: TrendItem,
          },
          props: true,
          meta: {isPublic: true},
        }
      ]
    },
  ],
  scrollBehavior (to, from, savedPosition) {
    if (savedPosition) {
      return savedPosition
    } else {
      return { x: 0, y: 0 }
    }
  }
})

to: 遷移先のルート情報
from: 遷移元のルート情報
savedPosition: ブラウザの戻る/進むボタンがトリガーされた時にのみ使う

上記だとブラウザ戻る、進むボタンが押された時以外はページトップに戻るようになっております。

特定のルートだけページ位置を戻したくない場合は、

.js
  scrollBehavior (to, from, savedPosition) {
    if (savedPosition || to.name == 'home' ||to.name == 'trend' || to.name == 'item') {
      return savedPosition
    } else {
      return { x: 0, y: 0 }
    }
  }

のようにto.nameで指定することで実装することができます。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?