3

I'd like to have query parameters in my Vue.JS application using vue-router like this:

http://localhost:8080/#/home/name=Alice&surname=Smith

I've added this route to my routes in the router.ts:

 routes: [{
    path: '/home/name=:name&surname=:surname',
    name: 'home',
    component: Home
 }]

What I want to do additionally is the following two things:

1) I want to be able to have the parameters name and surname in any order. E.g. these two URLs should lead to the same view:

http://localhost:8080/#/home/name=Alice&surname=Smith
http://localhost:8080/#/home/surname=Smith&name=Alice

2) I want them to be optional as well.

Is there a way to do these things? Thank you!

luthien
  • 1,285
  • 3
  • 15
  • 26

2 Answers2

6

To implement what you want you have to change the route:

routes: [{
    path: '/home',
    name: 'home',
    component: Home
}]

Open this route with query params:

router.push({ name: 'home', query: { name: 'Alice', surname: 'Smith' }});

The url will be (order of the query keys in the url doesn't matter):

http://localhost:8080/#/home?name=Alice&surname=Smith

And inside the route, you can get your query params as this.$route.query.name & this.$route.query.surname.

Check the documentation to get more info.

Max Martynov
  • 739
  • 5
  • 19
  • Thanks a lot for your answer. I'm still a bid confused though. In this way would it be possible to provide any values to the URL and reflect it to my view? I'd like the name and surname to be provided by the user through the URL and change on the fly. – luthien Aug 14 '18 at 08:05
  • Hi. If you still have problems, could you please describe the details more accurately? My answer should solve both your problems from your main question. Can you describe how your code works step by step and what you are going to do with the query params (name, surname) in the end? (it will be perfect if you can show a part of the code) – Max Martynov Aug 15 '18 at 13:03
  • I managed to solve my issue by having only one parameter called query and then parsing its contents in the JS part. Thank you for the help. – luthien Aug 17 '18 at 09:17
0

if you want to user in router link then use this

<router-link v-bind:to="{path:'/home' ,query: { name: 'helo' }}">home</router-link>"

then get this using this.$route.query.name

Umer Fayyaz
  • 357
  • 3
  • 12