Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
287 views
in Technique[技术] by (71.8m points)

vue.js - How can I make my vue router go to top of view?

I have the following problem: When I click on a new component link the router-view will not scroll to 0,0, but it will keep the scrolling state of the old component. It's supposed to move to the top but it doesn't...

https://re-solute.eu/

This is my router in vue

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes,
  scrollBehavior(to, from, savedPosition) {
    if (savedPosition) {
      return savedPosition
    } else {
      return { x: 0, y: 0 }
    }
  }
})

Thanks for your help!

question from:https://stackoverflow.com/questions/65845826/how-can-i-make-my-vue-router-go-to-top-of-view

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

try to modify the scrollBehavior

// scrollBehavior:
// - only available in html5 history mode
// - defaults to no scroll behavior
// - return false to prevent scroll
const scrollBehavior = (to, from, savedPosition) => {
 if (savedPosition) {
  // savedPosition is only available for popstate navigations.
  return savedPosition
 } else {
  const position = {}
  // new navigation.
  // scroll to anchor by returning the selector
  if (to.hash) {
   position.selector = to.hash
  }
  // check if any matched route config has meta that requires scrolling to top
  if (to.matched.some(m => m.meta.scrollToTop)) {
   // cords will be used if no selector is provided,
   // or if the selector didn't match any element.
   position.x = 0
   position.y = 0
  }
  // if the returned position is falsy or an empty object,
  // will retain current scroll position.
  return position
 }
}

You can also use routing meta information to control scrolling more finely

routes: [
 { path: '/', component: Home, meta: { scrollToTop: true }},
 { path: '/foo', component: Foo },
 { path: '/bar', component: Bar, meta: { scrollToTop: true }}
]

or you can reset the scroll bar to the top when switching routes

  watch: {
    '$route': function(to,from){
     document.body.scrollTop = 0
    }
  }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...