组件之间的vuejs路由滚动相同

时间:2016-08-17 12:12:34

标签: vue.js vue-router vue-component



<template>
    <div class="index">
        <common-header id="common-header" class="common-header" v-el:commonheader></common-header>
        <router-view transition keep-alive class="index-view"></router-view>
    </div>
</template>
&#13;
&#13;
&#13;

路径视图将显示两个组件A和B,而组件A scrollTop为0,我路由到组件B,向下滚动,然后路由到组件A,A也是滚动。有人有什么想法吗?

3 个答案:

答案 0 :(得分:1)

您可以在路由器之前添加一个全局挂钩,在每个路由转换开始之前调用它并滚动到页面顶部。这就是我解决它的方式。阅读here

Vue 1。

router.beforeEach(function (transition) {
 window.scrollTo(0, 0)
 transition.next()
})

对于Vue2:

 const router = new VueRouter({
   scrollBehavior (to, from, savedPosition) {
     return { x: 0, y: 0 }
   }
 })

参考here

答案 1 :(得分:0)

对于 Vuejs2.0 ,有一种新的可接受方式来处理页面更改时的滚动行为:

 import VueRouter from 'vue-router';
 const router = new VueRouter({
     scrollBehavior (to, from, savedPosition) {
         return { x: 0, y: 0 }
     }
 })

每次导航更改后,这将滚动到页面顶部。你可以read up on the full, official documentation about this functionality here

答案 2 :(得分:0)

我认为你滚动了错误的元素。我犯了同样的错误:组件A和组件B都在元素Body中,我使主体滚动,所以只要你移动滚动条,它将适用于A&amp; BI终于通过滚动组件而不是滚动正文来解决它。