Open In App

How to Get Query Parameters from a URL in VueJS ?

Last Updated : 31 Jan, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Query parameters are part of a URL that assigns values to specified parameters. They start after the question mark and are separated by ampersands (“&”) in the URL. For example, in the URL https://example.com?name=John&age=23, name=John and age=23 are query parameters. The below-listed methods can be utilized to get the query parameters from a URL in VueJS.

Setting Up the Project Environment

Step 1: Create a Vue.js application.

npm create vue@latest

Step 2: Navigate to your project directory and install dependencies:

cd your-project-name
npm install

Step 3: Install Vue Router.

npm install vue-router@4

Step 4: Create a Router File

Now, create a new folder named router and a file inside it named index.js. This index.js file will contain all the route configurations for our Vue.js application.

Step 5: Register vue router in main.js.

In this step Vue Router is integrated into our project by registering it in the main.js file. This step enables the application to utilize the capabilities of Vue Router, such as accessing and manipulating URL query parameters.

Step 6: Create a QueryParameters Component

To handle the display of query parameters, create a new file inside the views directory named QueryParameters.vue. This file will contain the Vue.js component that will fetch and display the query parameters from the URL.

Step 7: Create a Home Component

Inside the views directory, create a new file named HomeView.vue. This file will contain the Vue.js component that includes the navigation buttons.

Project Structure

Screenshot-2024-January-30-17-13

Using Vue Router’s useRoute hook

Vue Router, a routing library for Vue.js, provides a useRoute hook which can be used to access the current route. This route object encapsulates a query property that contains the query parameters.

Syntax:

const route = useRoute();
const queryParams = route.query;

Example: The below code example implements the useRoute hook of the Vue router to get query parameteres in the URL.

Javascript




<!-- QueryParameters.vue file -->
<template>
    <div id="container">
        <h2>
            Getting query parameters from URL
            Using Vue Router's useRoute hook
        </h2>
        <h3>
            Click the below button to get the
            query parameters.
        </h3>
        <button class="btn" @click="getQueryParams">
            Get Query Parameters
        </button>
        <div v-if="showQueryParams">
            <p v-if="queryParams.name">
                Below are the query parameters contained by the URL.
            </p>
            <p v-if="queryParams.name">Name: {{ queryParams.name }}</p>
            <p v-if="queryParams.age">Age: {{ queryParams.age }}</p>
            <p v-else>URL does not contain any query parameters</p>
        </div>
    </div>
</template>
 
<script>
    import { useRoute } from 'vue-router';
 
    export default {
        name: 'DisplayQueryParams',
        data() {
            return {
                queryParams: {},
                showQueryParams: false,
            };
        },
        setup() {
            const route = useRoute();
            return { route };
        },
        methods: {
            getQueryParams() {
                this.queryParams = this.route.query;
                this.showQueryParams = true;
            },
        },
    };
</script>
 
<style>
    #container {
        text-align: center;
    }
 
    .btn {
        color: #fff;
        background: green;
        border: none;
        padding: 10px;
        margin: 15px;
        border-radius: 5px;
        cursor: pointer;
    }
</style>


Javascript




<!-- HomeView.vue file -->
<template></template>
<script>
    export default {};
</script>
 
<style>
    .btn {
        color: #fff;
        background: green;
        border: none;
        padding: 10px;
        margin: 15px;
        border-radius: 5px;
        cursor: pointer;
    }
</style>


Javascript




<!-- App.vue file -->
<script>
    import { RouterView } from 'vue-router';
    import { useRouter } from 'vue-router';
 
    export default {
        setup() {
            const router = useRouter();
            return { router };
        },
        methods: {
            navigate() {
                this.router.push({ path: '/queryParameters' });
            },
            navigateWithQueryParams() {
                this.router.push(
                    {
                        path: '/queryParameters',
                        query: { name: 'John', age: '23'
                    }
                });
            },
        },
    };
</script>
 
<template>
    <div id="cont">
        <h1 style="color: green">GeeksforGeeks</h1>
        <h3>
            Click below buttons to change the URL and get
            query parameters if they are avaialble in the URL.
        </h3>
        <div>
            <button class="btn" @click="navigate">
                URL with no query params
            </button>
            <button class="btn" @click="navigateWithQueryParams">
                URL with query params
            </button>
        </div>
        <RouterView />
    </div>
</template>
 
<style>
    #cont {
        text-align: center;
    }
</style>


Javascript




// main.js
import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
 
const app = createApp(App)
 
app.use(router)
 
app.mount('#app')


Javascript




// router/index.js
import { createRouter, createWebHistory } from 'vue-router';
import HomeView from '../views/HomeView.vue';
import QueryParameters from '../views/QueryParameters.vue';
 
const router = createRouter({
    history: createWebHistory(),
    routes: [
        {
            path: '/',
            name: 'home',
            component: HomeView,
        },
        {
            path: '/queryParameters',
            name: 'QueryParameters',
            component: QueryParameters,
        },
    ],
});
 
export default router;


Output:

queryParamGIF

Using Vue Router’s $route in Options API

If you’re working with Vue 2 or prefer the Options API in Vue 3, you can leverage the this.$route object to access the query parameters.

Syntax:

const queryParams = this.$route.query;

Example: The below code implements the $route in the options API to get query parameters in URL.

Javascript




<!-- QueryParameters.vue file -->
<template>
    <div id="container">
        <h2>
            Getting query parameters from URL Using
            Router's $route in options API
        </h2>
        <h3>
            Click the below button to get the query parameters.
        </h3>
        <button class="btn" @click="getQueryParams">
            Get Query Parameters
        </button>
        <div v-if="showQueryParams">
            <p v-if="queryParams.name">
                Below are the query parameters contained by the URL.
            </p>
            <p v-if="queryParams.name">Name: {{ queryParams.name }}</p>
            <p v-if="queryParams.age">Age: {{ queryParams.age }}</p>
            <p v-else>URL does not contain any query parameters</p>
        </div>
    </div>
</template>
 
<script>
    import { useRoute } from 'vue-router';
 
    export default {
        name: 'DisplayQueryParams',
        data() {
            return {
                queryParams: {},
                showQueryParams: false,
            };
        },
        methods: {
            getQueryParams() {
                this.queryParams = this.$route.query;
                this.showQueryParams = true;
            },
        },
    };
</script>
 
<style>
    #container {
        text-align: center;
    }
 
    .btn {
        color: #fff;
        background: green;
        border: none;
        padding: 10px;
        margin: 15px;
        border-radius: 5px;
        cursor: pointer;
    }
</style>


Javascript




<!-- HomeView.vue file -->
<template></template>
<script>
    export default {};
</script>
 
<style>
    .btn {
        color: #fff;
        background: green;
        border: none;
        padding: 10px;
        margin: 15px;
        border-radius: 5px;
        cursor: pointer;
    }
</style>


Javascript




<!-- App.vue file -->
<script>
    import { RouterView } from 'vue-router';
    import { useRouter } from 'vue-router';
 
    export default {
        setup() {
            const router = useRouter();
            return { router };
        },
        methods: {
            navigate() {
                this.router.push({ path: '/queryParameters' });
            },
            navigateWithQueryParams() {
                this.router.push(
                    {
                        path: '/queryParameters',
                        query: { name: 'John', age: '23'
                    }
                });
            },
        },
    };
</script>
 
<template>
    <div id="cont">
        <h1 style="color: green">GeeksforGeeks</h1>
        <h3>
            Click below buttons to change the URL and get
            query parameters if they are avaialble in the URL.
        </h3>
        <div>
            <button class="btn" @click="navigate">
                URL with no query params
            </button>
            <button class="btn" @click="navigateWithQueryParams">
                URL with query params
            </button>
        </div>
        <RouterView />
    </div>
</template>
 
<style>
    #cont {
        text-align: center;
    }
</style>


Javascript




// main.js
import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
 
const app = createApp(App)
 
app.use(router)
 
app.mount('#app')


Javascript




// router/index.js
import { createRouter, createWebHistory } from 'vue-router';
import HomeView from '../views/HomeView.vue';
import QueryParameters from '../views/QueryParameters.vue';
 
const router = createRouter({
    history: createWebHistory(),
    routes: [
        {
            path: '/',
            name: 'home',
            component: HomeView,
        },
        {
            path: '/queryParameters',
            name: 'QueryParameters',
            component: QueryParameters,
        },
    ],
});
 
export default router;


Output:
queryParamGIF

Utilizing JavaScript’s URL and URLSearchParams

If you’d rather not use Vue Router or want a more JavaScript-centric approach, you can utilize the URL and URLSearchParams APIs to extract query parameters.

Syntax:

const url = new URL(window.location.href);
const queryParams = new URLSearchParams(url.search);

Example: The below code example uses the URL and URLSearchParams to get the query parameters in URL.

Javascript




<!-- QueryParameters.vue file -->
<template>
    <div id="container">
        <h2>
            Getting query parameters from URL Using URL
            and URLSearchParams
        </h2>
        <h3>
            Click the below button to get the query parameters.
        </h3>
        <button class="btn" @click="getQueryParams">
            Get Query Parameters
        </button>
        <div v-if="showQueryParams">
            <p v-if="queryParams.name">
                Below are the query parameters contained by the URL.
            </p>
            <p v-if="queryParams.name">Name: {{ queryParams.name }}</p>
            <p v-if="queryParams.age">Age: {{ queryParams.age }}</p>
            <p v-else>URL does not contain any query parameters</p>
        </div>
    </div>
</template>
 
<script>
    import { useRoute } from 'vue-router';
 
    export default {
        name: 'DisplayQueryParams',
        data() {
            return {
                queryParams: {},
                showQueryParams: false,
            };
        },
        methods: {
            getQueryParams() {
                const url = new URL(window.location.href);
                const params = new URLSearchParams(url.search);
                this.queryParams = Object.fromEntries(params);
                this.showQueryParams = true;
            },
        },
    };
</script>
 
<style>
    #container {
        text-align: center;
    }
 
    .btn {
        color: #fff;
        background: green;
        border: none;
        padding: 10px;
        margin: 15px;
        border-radius: 5px;
        cursor: pointer;
    }
</style>


Javascript




<!-- HomeView.vue file -->
<template></template>
<script>
    export default {};
</script>
 
<style>
    .btn {
        color: #fff;
        background: green;
        border: none;
        padding: 10px;
        margin: 15px;
        border-radius: 5px;
        cursor: pointer;
    }
</style>


Javascript




<!-- App.vue file -->
<script>
    import { RouterView } from 'vue-router';
    import { useRouter } from 'vue-router';
 
    export default {
        setup() {
            const router = useRouter();
            return { router };
        },
        methods: {
            navigate() {
                this.router.push({ path: '/queryParameters' });
            },
            navigateWithQueryParams() {
                this.router.push(
                    {
                        path: '/queryParameters',
                        query: {
                            name: 'John', age: '23'
                        }
                    });
            },
        },
    };
</script>
 
<template>
    <div id="cont">
        <h1 style="color: green">GeeksforGeeks</h1>
        <h3>
            Click below buttons to change the URL and get
            query parameters if they are avaialble in the URL.
        </h3>
        <div>
            <button class="btn" @click="navigate">
                URL with no query params
            </button>
            <button class="btn" @click="navigateWithQueryParams">
                URL with query params
            </button>
        </div>
        <RouterView />
    </div>
</template>
 
<style>
    #cont {
        text-align: center;
    }
</style>


Javascript




// main.js
import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
 
const app = createApp(App)
 
app.use(router)
 
app.mount('#app')


Javascript




// router/index.js
import { createRouter, createWebHistory } from 'vue-router';
import HomeView from '../views/HomeView.vue';
import QueryParameters from '../views/QueryParameters.vue';
 
const router = createRouter({
    history: createWebHistory(),
    routes: [
        {
            path: '/',
            name: 'home',
            component: HomeView,
        },
        {
            path: '/queryParameters',
            name: 'QueryParameters',
            component: QueryParameters,
        },
    ],
});
 
export default router;


Output:

queryParamGIF

Conclusion

Vue.js, coupled with Vue Router, offers a robust solution for managing URL query parameters. This feature is essential in creating dynamic and user-friendly web applications. Whether using the Vue Router or pure JavaScript, developers can efficiently retrieve and manipulate the state of the application from the URL.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads