Skip to content
Advertisement

How to use Vue router query params in hash mode?

I would like to access URL params in Vue methodology, other than using window.location.href and parsing.

router/index.js

const router = new Router({
  mode: 'hash',
  routes: []
});

router.beforeEach((to, from, next) => {
/*
*WOULD LIKE TO ACCESS THE URL PARAMS HERE*
**to.query** is not working in hash mode.
*/
})

Advertisement

Answer

The code you showed for logging the query params is correct so there is a problem with the route. To create a link in the template, use a <router-link>:

<router-link to="/myroute?id=5"></router-link>

To route programatically in the script, use this.$router.push (or this.$router.replace):

this.$router.push('/myroute?id=5');

When you log to.query, you should see:

{ id: "5" }

Edit: You revealed (in comments) that you are linking to the app externally.

Linking from an external site in hash mode

http://localhost/#/?id=5

When linking to the site externally in hash mode, you have to use the hash in the url or the query won’t be registered properly. The query has to follow the hash, but will be placed in front of it if the hash isn’t used.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement