8

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
  • 59,490
  • 13
  • 101
  • 110
Nanda Z
  • 1,604
  • 4
  • 15
  • 37

3 Answers3

25

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 (Not recommended)

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
  • 59,490
  • 13
  • 101
  • 110
3

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
  • 84
  • 4
0

For Vue Router 4 :: Compositon API :: Vue3

Router-link attach params

 <router-link
    style="width: 100%"
    class="btn btn-success btn-block edit"
    :to="{ name: 'editUser',params: {id: user.id}}">
       <i class="fa-solid fa-user-gear"></i>
 </router-link>

In a page you are receiving,

<script>

export default {
  props: ["id"],
  setup(props, context) {
        console.log(props.id);
  },
};
</script>

In Your app.js

import { createApp } from 'vue';
...
...
const app = createApp(root);

app.use(router);

router.isReady().then(() => {
    app.mount('#app');
})
Saugat
  • 1
  • 3