Vue.js滚动到同一路线的页面顶部

vue.js Vue.js

Davaid阳光

2020-03-12

我可以将滚动行为设置为Vue.js Router,如下所示:

const router = new Router({
    mode: 'history',
    routes: [
        {
            path: '/',
            name: 'index',
            component: Main
        },
        {
            path: '/some-path',
            name: 'some-path',
            component: SomePath
        }
    ],
    scrollBehavior() {
        return {x: 0, y: 0}
    }
})

当您单击带有当前页面之外的页面的链接时,这种方法非常有效。当我单击已经渲染的链接时,即在页脚中,什么也没有发生。Vue路由器假定没有状态转换。在这种情况下,向上滚动的首选方式是什么?

第1011篇《Vue.js滚动到同一路线的页面顶部》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

6个回答
ProTony 2020.03.12

使用这个不错的组件:https : //www.npmjs.com/package/vue-backtotop

<back-to-top text="Back to top"></back-to-top>
凯LEY 2020.03.12

如果浏览器支持history.pushState,则Vue Js具有内置的滚动支持

创建Vue路由器实例时,配置非常容易,只需提供scrollBehavior函数,如下所示:

const router = new VueRouter({
  routes: [...],
  scrollBehavior (to, from, savedPosition) {
    // page scroll to top for all route navigations
    return { x: 0, y: 0 }
  }
})

有关Vue 滚动行为的 更多选项和详细信息,请单击此处。

泡芙达蒙 2020.03.12

基本上,除非您指定内部页面位置(例如,www.example.com / home#blah),否则我认为您想滚动到页面顶部。到目前为止,所有答案都将忽略此location参数,无论如何只是滚动到顶部。

scrollBehavior(to, from, savedPosition) {
    //If there is no hash parameter when we change vue, scroll to top of page
    if (!to.hash) {
      return { x: 0, y: 0 }
    }
  }

我们可以使用来检查是否有位置参数to.hash,然后仅在不存在哈希位置的情况下滚动到顶部。

GO 2020.03.12

我为此找到的最佳解决方案是:https : //router.vuejs.org/guide/advanced/scroll-behavior.html

特别:

const router = new VueRouter({
  routes: [...],
  scrollBehavior (to, from, savedPosition) {
    return { x: 0, y: 0 }
  }
})
番长 2020.03.12

使用refs了滚动某些部分

<template>
  <body>
    <div ref="section">
      // Your content section
    </div>
  </body>
</template>

export default class MyPage extends Vue {
  $refs!: {
    section: HTMLFormElement;
  };

  scrollToTop() {
    this.$refs.section.scrollTo(0, 0);
  }
}
樱小小Tom 2020.03.12

您无法执行此槽形vue-router。但是您可以将滚动到顶部的方法添加到每个路由器链接。

只需创建一个方法

 methods: { 
           scrollToTop() {
                window.scrollTo(0,0);
           }
        }

并将其添加到链接

<router-link @click.native="$scrollToTop">

如果您也想在页脚之外使用它,最好将其添加到Vue原型中

Vue.prototype.$scrollToTop = () => window.scrollTo(0,0)

这不是100%的解决方案,但这是最简单的解决方案

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android