10

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

4 Answers 4

28

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);
}
Sign up to request clarification or add additional context in comments.

Comments

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

2 Comments

Sorry, but thats not what i want. i need to use query params pattern, not slug
I think this might come in handy one day, just not today.
1

Accessing the query needs get query from currentRoute. currentRoute is Ref type so the query must be gotten from the value property.

<script setup lang="ts">

import { useRouter } from 'vue-router'; 
const router = useRouter();
console.log(router.currentRoute.value.query.ProjectId)

</script>

Comments

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');
})

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.