How can I get query parameters from a URL in Vue.js?
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() {
},
....
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"
},
});
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'