1

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

Ollie
  • 1,104
  • 7
  • 24
  • 45
  • 2
    Possible duplicate of [How can I get query string values in JavaScript?](https://stackoverflow.com/questions/901115/how-can-i-get-query-string-values-in-javascript) – Roy J Sep 24 '17 at 15:45

2 Answers2

3

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

Adi Azarya
  • 4,015
  • 3
  • 18
  • 26
1

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

Tony
  • 16,527
  • 15
  • 80
  • 134