javascriptvue.jsvue-router4

Vue Router not finding query params


Vue 3, Vue Router 4, web hash history router

I have a url with a query param that gets inserted, but Vue seems to ignore it and it's causing weird redirect issue for my application.

For example:

Is: Https://example.com/?foo=bar#/

Should be: Https://example.com/#/?foo=bar

I don't know why the #/ is getting stuck on the end and Vue must be looking after that to find any query params, so that seems to be why it's not being found. Any ideas?


Solution

  • In your case it should be :

    Https://example.com/#/?foo=bar
    

    With that update your router configurations as below:

    import {
      createRouter,
      createWebHashHistory
    } from 'vue-router';
    
    const routes = [
      // define the routes here
    ];
    
    const router = createRouter({
      history: createWebHashHistory(), // make sure to call webHashHistory() here
      routes,
    });
    
    export default router;

    in you main.js:

    import {  createApp } from 'vue';
    import App from './App.vue';
    import router from './router';
    
    const app = createApp(App);
    
    router.beforeEach((to, from, next) => {
      const url = new URL(window.location.href);
      const searchParams = url.search;
      if (searchParams) {
        const newUrl = url.origin + url.pathname + '/#/' + searchParams;
        window.location.replace(newUrl);
      } else {
        next();
      }
    });
    
    app.use(router).mount('#app');

    Via doing so you can redirect incorrect URLs (query params before # mark). You can add a redirection logic to your application.