0

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?

1
  • "I have a url with a query param that gets inserted" - in which way? Please, provide a way to reproduce. Since you stated that hash router is used, it's reasonable that router will use #/... part and ignore the rest, that's what the choice of hash router is responsible for Commented Jul 23, 2024 at 15:01

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.