Ollie
Ollie

Reputation: 1134

Access the query string in VueJS

I've just started using VueJS and I'm really liking it! :) I would like to save the values in the querystring to a VueJS variable - this is something super simple in handlebars + express, but seems more difficult in Vue.

Essentially I am looking for something similar to -

http://localhost:8080/?url=http%3A%2F%2Fwww.fake.co.uk&device=all


const app = new Vue({
    ...
    data: {
        url: req.body.url,
        device: req.body.device
    }
    ...
});

Google seemed to point me to vue-router, but I'm not sure if that's really what I need/how to use it. I'm currently using express to handle my backend logic/routes.

Thanks,

Ollie

Upvotes: 1

Views: 3126

Answers (2)

Tony
Tony

Reputation: 17637

You can use URLSearchParams and this polyfill to ensure that it will work on most web browsers.

// Assuming "?post=1234&action=edit"
var urlParams = new URLSearchParams(window.location.search);

console.log(urlParams.has('post')); // true
console.log(urlParams.get('action')); // "edit"
console.log(urlParams.getAll('action')); // ["edit"]
console.log(urlParams.toString()); // "?post=1234&action=edit"
console.log(urlParams.append('active', '1')); // "?post=1234&action=edit&active=1"

Source: https://davidwalsh.name/query-string-javascript

URLSearchParams
https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams
https://github.com/WebReflection/url-search-params/blob/master/build/url-search-params.js

See also:
https://stackoverflow.com/a/12151322/194717

Upvotes: 1

Adi Azarya
Adi Azarya

Reputation: 4473

You can either to put all your parameters in hash of the url, e.g.:

window.location.hash='your data here you will have to parse to'

and it will change your url - the part after #

Or if you insist to put them as query parameters (what's going after ?) using one of the solutions from Change URL parameters

Upvotes: 3

Related Questions