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