vue路由器强制popstate

vue router forcing popstate

我在页面中间有一些 links,它们使用嵌套路由器更改其下方窗格中的内容。我遇到这个问题的路线看起来像这样:

const router = {
  mode: 'history',
  routes: [
    {
      path: '/parent',
      name: 'ParentComponent',
      component: ParentComponent,
      children: [
        {
          path: 'child1',
          name: 'Child1',
          component: Child1,
        },
        {
          path: 'child2',
          name: 'Child2',
          component: Child2,
        },
      ],
    },
  ],
}

问题是内容向下滚动页面,当我点击 link 到子路径时,它跳到顶部。所以我尝试添加 scrollBehavior 来保持滚动位置,如下所示:

router.scrollBehavior = (to, from, savedPosition) => {
  console.log('savedPosition: ', savedPosition);
  if (savedPosition) {
    return savedPosition;
  }
  return { x: 0, y: 0 };
}

这个console.log总是为我输出null。在阅读 docs 时,它表示 savedPosition 只有在 popstate 导航时才具有值。

有没有一种方法可以强制执行 link 执行 popstate 导航,或者是否有另一种方法可以用来在我单击 link?

我最近做了这样的事情

scrollBehavior (to, from) {
  if (to.path === from.path && to.query && to.query.page === from.query.page) {
    return false
  } else {
    return { x: 0, y: 0 }
  }
},

这可能会让你走上正轨

这正是链接docs中所说的。

The scrollBehavior function receives the to and from route objects. The third argument, savedPosition, is only available if this is a popstate navigation (triggered by the browser's back/forward buttons).

由于您是使用页面中间的链接触发导航,因此它不是弹出状态导航。

因此正确的做法是不使用该函数的 savedPosition 版本,因为不会设置该位置。