vue.jsvue-routerscrolltop

How to get scroll behavior to work with this setup in Vue 3?


I have tried various iterations of scrollBehavior and haven't been able to get it working with this setup. I have tried adding it to all routes, I have tried adding meta data to each route and doing it that way. Nothing seems to work and the Vue app won't scroll to top. Here is where I am at:

import { createRouter, createWebHistory } from 'vue-router'
import HomeView from '../views/HomeView.vue'
import MusicView from '../views/MusicView.vue'
import GenreView from '../views/GenreView.vue'
import AboutView from '../views/AboutView.vue'
import MusicFiltersView from '../views/MusicFiltersView.vue'

const router = createRouter({

history: createWebHistory(import.meta.env.BASE_URL),

scrollBehavior(to){
const scroll = {}
if (to.meta.toTop) scroll.top = 0
if (to.meta.smoothScroll) scroll.behavior = 'smooth'
return scroll
},

routes: 

[
{
  path: '/',
  component: HomeView,
  meta: {toTop: true, smoothScroll: true}
},
{
  path: '/music',
  component: MusicView,
  meta: {toTop: true, smoothScroll: true}
},
{
  path: '/about',
  component: AboutView,
  meta: {toTop: true, smoothScroll: true}
},
{
  path: '/genres',
  component: GenreView,
  meta: {toTop: true, smoothScroll: true}
},
{
  path: '/music-filters',
  component: MusicFiltersView,
  meta: {toTop: true, smoothScroll: true}
},
],

 })

 export default router 

This is using Vue 3.


Solution

  • In this case, this was the answer:

    const router = createRouter({   history: createWebHashHistory(),   routes,   scrollBehavior() {     document.getElementById("RouterView").scrollTop = 0;   }, });