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, that expose what you need. In this case
//from your component
console.log(this.$route.query.test) // outputs 'yay'
More detailed answer to help the newbies of VueJs.
<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)
},
});
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(){
},
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.)
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
As of this date, the correct way is (i don't know why they've changed):
this.$route.params.yourProperty instead of this.$route.query.yourProperty
来源:https://stackoverflow.com/questions/35914069/how-can-i-get-query-parameters-from-a-url-in-vue-js