【问题标题】:Vue Router - Changing to history mode in an existing application and handling old bookmarksVue Router - 在现有应用程序中更改为历史模式并处理旧书签
【发布时间】:2020-09-28 01:17:57
【问题描述】:

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

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

我必须使用 router.replace 来去掉“#”还是有更好的方法?

我查看了许多解决方案,但没有一个(我检查过)谈论我正在为现有应用程序切换到“历史”模式的场景

【问题讨论】:

标签: vue.js vue-router bookmarks


【解决方案1】:

在我的情况下,所有新页面都是在设置历史模式后引入的(条件&& 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' 并将替换设置为 true。对我有用。

【讨论】:

    猜你喜欢
    • 2017-05-23
    • 2018-07-07
    • 2017-12-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-09
    • 2017-02-04
    • 2018-05-17
    相关资源
    最近更新 更多