Rob
Rob

Reputation: 11388

How can I get query parameters from a URL in Vue.js?

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?

Upvotes: 567

Views: 648449

Answers (16)

Noobogami
Noobogami

Reputation: 116

if you don't want to use router and want a one line solution you can write this:

new URL(window.location.toString()).searchParams.get("test")

Upvotes: 0

Yerko Palma
Yerko Palma

Reputation: 12339

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'

Upvotes: 741

TAHER El Mehdi
TAHER El Mehdi

Reputation: 9213

Instead of each time you want to call a param you have to call $route then params then your param this.$route.params.parma1, this.$route.params.parma2, this.$route.params.parmaX

Why not doing it in computed:

  computed: {
    params:function () {
      return this.$route.params;
    }

then simply calling it from params is much more readable and easy to use : this.params.parma1, this.params.parma2, this.params.parmaX

Upvotes: 1

kissu
kissu

Reputation: 46774

On top of the answers here, I recommend that you use the Vue devtools for further debugging.

Given this snippet of code

<template>
  <div>
    {{ showOrNotTheMessage }}
  </div>
</template>

<script>
export default {
  computed: {
    showOrNotTheMessage() {
      return this.$route.query?.lookingforthis
        ? 'Show this message'
        : 'Dont show this message'
    },
  },
}
</script>

This one will mainly display a conditional string as an example.


If you want to further debug what you're doing (with either Options or Composition API), you can select the root component in your Vue devtools and then access the whole Vue instance in your console with

$vm0.$route.query

PS: in Vue3, you need to use the following to access the Vue instance via the Devtools.

$vm0.proxy.$route.params.query

enter image description here

That can help you debug your code faster and potentially find cool stuff to play with.

Upvotes: 5

Adeel Raza Azeemi
Adeel Raza Azeemi

Reputation: 813


Vue 3 Composition :


first include you router

import router from '../../router'

then to access the for example the id; use

 router.currentRoute.value.params.id

Upvotes: 1

Sabyasachi
Sabyasachi

Reputation: 1554

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)
    },
});

Upvotes: 61

erajuan
erajuan

Reputation: 2294

Without vue-router, 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() {
  },
....

Upvotes: 101

Alexandr
Alexandr

Reputation: 1031

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

Upvotes: 51

Roland
Roland

Reputation: 27769

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

Upvotes: 6

Correcter
Correcter

Reputation: 3686

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"
  },
});

Upvotes: 105

Mike P
Mike P

Reputation: 2877

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.)

Upvotes: 54

Muhammad
Muhammad

Reputation: 387

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

Upvotes: 1

duyuanchao
duyuanchao

Reputation: 4313

Example url: http://localhost:9528/#/course/outline/1439990638887137282

Below codes output: 1439990638887137282

this.courseId = this.$route.params.id
console.log('courseId', this.courseId)

Upvotes: 2

devnomic
devnomic

Reputation: 707

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)
  }
}

Upvotes: 6

NobodySomewhere
NobodySomewhere

Reputation: 3225

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

Upvotes: 6

Marco
Marco

Reputation: 2922

As of this date, the correct way according to the dynamic routing docs is:

this.$route.params.yourProperty

instead of

this.$route.query.yourProperty

Upvotes: 17

Related Questions