Home > Blockchain >  What are the implications of migrating from createWebHashHistory() to createWebHistory()?
What are the implications of migrating from createWebHashHistory() to createWebHistory()?

Time:03-26

I have an application that I released that uses createWebHashHistory() to manage URLs. For example, a user visits the following URL to visit something called the earthquakes channel:

https://app.radar.chat/#/channel/earthquakes

I would like to switch over to using createWebHistory() to manage URLs instead (SEO, social media previews, iOS universal links configuration, etc). With that in mind, I would like it if my new URL structure looks like this:

https://app.radar.chat/channel/earthquakes

I know that to support this change I need to make a server change. The easiest way is to have the server redirect incoming requests to an index.html file (this is documented extensively on the Vue website).

However, there are URLs in the wild that link to these old pages, URLs that have been printed and that can never be updated.

Is there a convenient mechanism to continue to support the old hash-based URLs while having the non-hashed URLs be the new default?

CodePudding user response:

In your router config, you could add a global beforeEach hook on the index path that resolves to the hash path in the URL if it exists:

// router.js
import { createRouter, createWebHistory } from 'vue-router'

const router = createRouter({
  history: createWebHistory(),
  routes: [⋯]
})

router.beforeEach((to, from, next) => {
  if (to.path === '/' && to.hash.startsWith('#/')) {
    next(to.hash.substr(1))
  } else {
    next()
  }
})

export default router

demo

  • Related