【问题标题】:How can I make my vue router go to top of view?如何让我的 vue 路由器进入视图顶部?
【发布时间】:2021-04-26 23:02:00
【问题描述】:

我有以下问题: 当我单击新组件链接时,路由器视图不会滚动到 0,0,但会保持旧组件的滚动状态。它应该移动到顶部,但它没有......

https://re-solute.eu/

这是我在 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 }
    }
  }
})

感谢您的帮助!

【问题讨论】:

    标签: vue.js vue-router


    【解决方案1】:

    尝试修改滚动行为

    // 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
     }
    }
    

    你还可以使用路由元信息来更精细地控制滚动

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

    或者您可以在切换路线时将滚动条重置为顶部

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

    【讨论】:

      【解决方案2】:

      我遇到了同样的问题,它适用于以下解决方法。

      尝试第一个:

      scrollBehavior() {
              document.getElementById('app').scrollIntoView();
          }
      

      如果还是同样的问题,试试这个:

      App.vue
      
      
      
      <transition @before-enter="scrollTop" mode="out-in" appear>
        <router-view></router-view>
      </transition>
      
      
      
      methods: {
        scrollTop(){
         document.getElementById('app').scrollIntoView();
        },
      }
      

      【讨论】:

        猜你喜欢
        • 2017-03-06
        • 2019-04-01
        • 2020-07-01
        • 2023-03-06
        • 1970-01-01
        • 1970-01-01
        • 2020-01-19
        • 2019-05-10
        • 1970-01-01
        相关资源
        最近更新 更多