How can I fetch query parameters in Vue.js?
E.g.
http://somesite.com?test=yay
Can’t find a way to fetch or do I need to use pure JS or some library for this?
According to the docs of route object, you have access to a $route
object from your components, which exposes what you need. In this case
//from your component
console.log(this.$route.query.test) // outputs 'yay'
Without vue-route, split the URL
var vm = new Vue({
....
created() {
let uri = window.location.href.split('?');
if(uri.length == 2) {
let vars = uri[1].split('&');
let getVars = {};
let tmp = '';
vars.forEach(function(v) {
tmp = v.split('=');
if(tmp.length == 2)
getVars[tmp[0]] = tmp[1];
});
console.log(getVars);
// do
}
},
updated() {
},
....
Another solution https://developer.mozilla.org/en-US/docs/Web/API/HTMLHyperlinkElementUtils/search:
var vm = new Vue({
....
created() {
let uri = window.location.search.substring(1);
let params = new URLSearchParams(uri);
console.log(params.get("var_name"));
},
updated() {
},
....
location.href
yourself when there is location.search
readily available? developer.mozilla.org/en-US/docs/Web/API/… e.g. var querypairs = window.location.search.substr(1).split('&');
Also splitting the query name-value pairs by '=' will not always work as you can pass named query parameters without value as well; e.g. ?par1=15&par2
Your code would now raise an exception on par2 as splitting by '=' will result in tmp with only 1 element.
undefined
to getVars['par2']
.
.substring(1)
seems to be unnecessary
Try this code
var vm = new Vue({
created() {
let urlParams = new URLSearchParams(window.location.search);
console.log(urlParams.has('yourParam')); // true
console.log(urlParams.get('yourParam')); // "MyParam"
},
});
More detailed answer to help the newbies of VueJS:
First define your router object, select the mode you seem fit. You can declare your routes inside the routes list.
Next you would want your main app to know router exists, so declare it inside the main app declaration.
Lastly the $route instance holds all the information about the current route. The code will console log just the parameter passed in the url. (*Mounted is similar to document.ready, i.e. it's called as soon as the app is ready)
And the code itself:
<script src="https://unpkg.com/vue-router"></script>
var router = new VueRouter({
mode: 'history',
routes: []
});
var vm = new Vue({
router,
el: '#app',
mounted: function() {
q = this.$route.query.q
console.log(q)
},
});
<script src="https://unpkg.com/vue-router"></script>
new Vue({ router, ... })
is not valid syntax.
Another way (assuming you are using vue-router
), is to map the query param to a prop in your router. Then you can treat it like any other prop in your component code. For example, add this route;
{
path: '/mypage',
name: 'mypage',
component: MyPage,
props: (route) => ({ foo: route.query.foo }),
}
Then in your component you can add the prop as normal;
props: {
foo: {
type: String,
default: null,
}
},
Then it will be available as this.foo
and you can do anything you want with it (like set a watcher, etc.)
As of this date, the correct way according to the dynamic routing docs is:
this.$route.params.yourProperty
instead of
this.$route.query.yourProperty
query
to get the queries from the URL. From the docs: In addition to $route.params, the $route object also exposes other useful information such as $route.query (if there is a query in the URL)
{ path: '/user/:id' }
, the url /user/123?a=b&c=d
will have $route.params == { id: "123" }
and $route.query == { a: "b", c: "d" }
.
params
means the parameters in your URL
like /user/:username
. You see that the username
is params
but query params
are alike this /search/?q='new Vue js'
, As you see, the new Vue js
is a query param here. And there is nothing in the document that proves your answer. Please tell me which line of the document you see those?
Vue 3 Composition API
(as far as now 2021, vue-router 4)
import {useRoute} from "vue-router";
//can use only in setup()
useRoute().query.test
or
//somewhere in your src files
import router from "~/router";
//can use everywhere
router.currentRoute.value.query.test
or
import {useRouter} from "vue-router";
//can use only in setup()
useRouter().currentRoute.value.query.test
If your url looks something like this:
somesite.com/something/123
Where '123' is a parameter named 'id' (url like /something/:id), try with:
this.$route.params.id
You can use vue-router.I have an example below:
url: www.example.com?name=john&lastName=doe
new Vue({
el: "#app",
data: {
name: '',
lastName: '',
},
beforeRouteEnter(to, from, next) {
if(Object.keys(to.query).length !== 0) { //if the url has query (?query)
next(vm => {
vm.name = to.query.name;
vm.lastName = to.query.lastName;
});
}
next();
}
})
Note: In beforeRouteEnter
function we cannot access the component's properties like: this.propertyName
.That's why i have pass the vm
to next
function.It is the recommented way to access the vue instance.Actually the vm
it stands for vue instance
site.com/route?query=test
the query
param returns undefined
when accessed via the to
param in the beforeRouteEnter(to, from, next)
method. Any ideas why this could be so?
Here is how to do it if you are using vue-router
with vue3 composition api
import { useRoute } from 'vue-router'
export default {
setup() {
const route = useRoute()
console.log(route.query)
}
}
Example url: http://localhost:9528/#/course/outline/1439990638887137282
Below codes output: 1439990638887137282
this.courseId = this.$route.params.id
console.log('courseId', this.courseId)
one thing to keep in mind if you are using Hash mode then don't use this.$route.params.name only use url search param
You can get By Using this function.
console.log(this.$route.query.test)
Success story sharing
vue-router
than this would indeed be a duplicate, as he will need to use standard JS methods.vue-router
tag and added it.return next({ name: 'login', query:{param1: "foo" }, });
doesn't work. inside the login component the propparam1
is undefined.