Vue Router - 在现有应用程序中更改为历史模式并处理旧书签

Vue Router - Changing to history mode in an existing application and handling old bookmarks

我有一个应用程序在 vue 路由器设置中没有使用 'history' 模式。所以所有现有的 URL 都有一个“/#/”。示例 - ~/#/login~/#/page1

当我添加模式时:'history',新的 url 效果很好。 但是,如果我尝试使用仍然带有“#”的旧书签,路由将失败。

我是否必须使用 router.replace 来去掉“#”,或者有更好的方法吗?

我查看了很多解决方案,但 none(我检查过)谈到了我正在为现有应用程序切换到 'history' 模式的场景

在我的案例中,所有新页面都是在设置历史模式后引入的(条件 && to.name !== 'newPage' 非常适合我的案例),所以对我有用的解决方案是

router.beforeEach((to, from, next) => {
  const redirectPath = to.hash.split('#')[1]
  if (to.hash && to.name !== 'newPage') {
    next({
      path: redirectPath,
      hash: '',
      replace: true
    })
  }

...
return next()
}

在这种情况下,如果我使用我的旧书签(比如 ~/#/page1),to.hash 保存值“#/page1”,所以我所做的就是将散列拆分为 ["" , "/page1"] 然后将 next() 中的路径设置为 '/path1' 并将 replace 设置为 true。适合我。