The query parameters are key-value pairs that you see in a URL after the ?
symbol.
https://example.com/search?q=dogs&time=week
If we are using the <router-link>
component, we can pass the query parameters using the:to
attribute.
<router-link :to="{path:'/products',query:{id: 1}}">
Product
</router-link>
The :to
attributes takes router object with query
key where we can define all the query parameters.
To set the query parameters dynamically, we can make use of the $router.push()
method.
this.$router.push({ path: "/products", query: { id: 1 } });
In this article, we will look at how to set the query parameters and also how to get their values in the Vue CLI application.
We will begin by creating a new application using Vue CLI.
❯ vue create query-parameters-demo
Once, the installation is complete, we can navigate to the folder and run the server to load the application.
❯ cd query-parameters-demo
❯ npm run serve
This will run our server on port 8080 by default http://localhost:8080/
Next, we will install the vue-router
package required for routing. We can install it using CDN, npm or yarn.
npm:
npm install vue-router@4
yarn:
yarn add vue-router@4
Once the package is installed, we can integrate it with our Vue.js application.
Next, we will create a component TheProduct
touch src/components/TheProduct.vue
Let’s add some code to display the product id.
<!-- TheProduct.vue -->
<template>
<h2>Product</h2>
</template>
We will make changes to the main.js
file to include the router configuration.
// main.js
import { createApp } from "vue";
import { createRouter, createWebHistory } from "vue-router";
import App from "./App.vue";
import TheProduct from "./components/TheProduct";
const app = createApp(App);
const router = createRouter({
history: createWebHistory(),
routes: [
{
path: "/product/:id",
component: TheProduct,
name: "product",
},
],
});
app.use(router);
app.mount("#app");
Let’s edit App.vue
file and use the <router-link>
and $router.push()
method to pass the query parameters.
<!-- App.vue -->
<template>
<div>
<router-link
:to="{
name: 'product',
params: { id: 1 },
query: { name: 'first_product' },
}"
>
Product 1
</router-link>
</div>
<div>
<button @click="goToProduct">Product 2</button>
</div>
<router-view></router-view>
</template>
<script>
export default {
name: "App",
methods: {
goToProduct() {
this.$router.push({
name: "product",
params: { id: 2 },
query: { name: "second_product" },
});
},
},
};
</script>
<style>
div {
margin: 20px;
}
</style>
In this case, we are passing name
as the query parameter using both the <router-link>
and $router.push()
method.
To access the query parameter in the TheProduct
component we can make use of the $route.query.name
.
<!-- TheProduct.vue -->
<template>
<h2>Product id: {{ $route.params.id }}</h2>
<h3>Product name: {{ $route.query.name }}</h3>
</template>
Let’s look at the output:
This is how you can make use of the query parameters in Vue.js!