Sometimes, we may want to add query parameters to route URLs so that we can get the query parameters in the component.
In this article, we’ll look at how to get query parameters from a URL in a Vue 3 app that uses Vue Router 4.
Get Query Parameters from a URL in Vue.js 3 with Vue Router 4
To get query parameter from a URL in a Vue 3 app that uses Vue Router 4, we can get the query parameters from the this.$route.query
property.
main.js
import { createApp } from "vue";
import { createRouter, createWebHistory } from "vue-router";
import App from "./App.vue";
import Page1 from "./views/Page1";
import Page2 from "./views/Page2";
import Page3 from "./views/Page3";
const routes = [
{ path: "/", component: Page1 },
{ path: "/page2", component: Page2 },
{ path: "/page3", component: Page3 }
];
const router = createRouter({
history: createWebHistory(),
routes
});
const app = createApp(App);
app.use(router);
app.mount("#app");
App.vue
<template>
<router-link to="/">page 1</router-link>
<router-link to="/page2">page 2</router-link>
<router-link to="/page3">page 3</router-link>
<router-view></router-view>
</template>
<script>
export default {
name: "App"
};
</script>
views/Page1.vue
<template>
<div>page 1</div>
</template>
views/Page2.vue
<template>
<div>page 2</div>
</template>
views/Page3.vue
<template>
<div>page 3 {{ $route.query.foo }}</div>
</template>
<script>
export default {};
</script>
We set up the routes in main.js
.
We import the page components and put them in the routes
array.
Next, we call createRouter
to create the router
object.
Then we add the routes
to the object we pass into createRouter
,
Then we have:
app.use(router);
to add the router
to our app.
In Page3.vue
, we have $router.query.foo
in the template to get the foo
query parameter.
This is the same as this.$router.query.foo
in the component object.
In App.vue
, we have the 3rd router-link
‘s to
prop with a query string added after the path.
So when we click the link, we should see ‘bar’ displayed since we have foo=bar
in the query string.
Conclusion
We can get query parameters in our Vue 3 app that uses Vue Router 4 with the this.$route.query
property in a component.