5

I want to make search page which after I click its button will be redirected to another page. And this page will be like this

http://localhost:8080/search?q=foo

and my router index.js looks like this

const routers = [
  {
    path: '/search',
    name: 'Search',
    component: SearchPage,
    props: route => ( { query: route.query.q } )
  }
]

and the question is how do i get the query value in target page SearchPage, in Vue.js 3? This Answer is still confusing me, because not using composition API and not in vuejs 3

Dan
  • 52,223
  • 13
  • 79
  • 96
Nanda Z
  • 1,303
  • 11
  • 30

2 Answers2

8

Using useRoute

You don't need to send the query as a prop. It's better to use useRoute because it's simpler and it can be accessed from any component, not just the page view component.

import { useRoute } from 'vue-router';

export default {
  setup() {
    const route = useRoute();
    console.log(route.query);
  }
}

Using a prop

First change the router mapping so that query maps to the query object:

props: route => ({ query: route.query })

In the destination component, SearchPage, create a query prop which will receive the query object from the router:

props: ['query']

And access it in setup via the props argument:

props: ['query'],
setup(props) {
  console.log(props.query.q);
  console.log(props.query.status);
}
Dan
  • 52,223
  • 13
  • 79
  • 96
  • What to do if I do not use vue-router? – aProgger Feb 10 '22 at 13:19
  • @aProgger - Start using it. Otherwise, you can use [vanilla Javascript](https://stackoverflow.com/questions/901115/how-can-i-get-query-string-values-in-javascript/901144#901144) – Dan Feb 10 '22 at 17:20
  • meeh, hoped there is a fancy vue way (without router). – aProgger Feb 11 '22 at 12:07
  • you can use ```(route) => ({ ...route.query })``` and not have to use the nested query object – Matt Broekhuis Feb 23 '22 at 03:41
  • @MattBroekhuis - That's true, though I usually stick to the format used in the question. Otherwise you run the risk of confusing OP or breaking their other code. (Answer enough questions and you'll know what I mean.) – Dan Feb 23 '22 at 04:15
2

another setup you can try, send propname by url { path: '/search/:propname', name: 'Search', component: SearchPage, props: true }, and on searchpage, on created() you can get recive it this.$route.params.propname

talm0r
  • 54
  • 3