In Vue.js, we can retrieve query parameters from a URL using the this.$route.query object. Here’s how we can access query parameters in a Vue.js component:
- If we’re using Vue Router, ensure that our component has access to the
$routeobject.
We can typically access this object within a component that is rendered by a route.
- Access the
queryobject from$route. This object contains all the query parameters parsed from the URL.
Here’s an example of how we can access query parameters in a Vue.js component:
<template>
<div>
<p>Query Parameters:</p>
<ul>
<li v-for="(value, key) in queryParams" :key="key">
{{ key }}: {{ value }}
</li>
</ul>
</div>
</template>
<script>
export default {
data() {
return {
queryParams: {}
};
},
created() {
// Access query parameters from $route
this.queryParams = this.$route.query;
}
};
</script>
In this example we access the query parameters in the created lifecycle hook of the component.
We assign the query parameters to the queryParams data property.
In the template, we loop through the queryParams object using v-for to display each query parameter and its value.
With this setup, the component will display all query parameters and their values passed in the URL.
For example, if our URL is http://example.com/?param1=value1¶m2=value2, the component will display:
Query Parameters:
- param1: value1
- param2: value2
We can then use these query parameters within our Vue.js component as needed.