在 VueJS 中访问查询字符串

Access the query string in VueJS

我刚开始使用 VueJS,我真的很喜欢它! :) 我想将查询字符串中的值保存到 VueJS 变量中——这在 handlebars + express 中非常简单,但在 Vue 中似乎更难。

基本上我正在寻找类似于 -

的东西
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 似乎将我指向 vue-router,但我不确定这是否真的是我 need/how 使用它的目的。我目前正在使用 express 来处理我的后端 logic/routes.

谢谢,

奥利

您可以将所有参数放在 url 的散列中,例如:

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

它会改变你的 url - #

之后的部分

或者如果您坚持使用 Change URL parameters

中的一种解决方案将它们作为查询参数(? 之后发生的事情)

您可以使用 URLSearchParamsthis polyfill 来确保它可以在大多数网络浏览器上运行。

// 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"

来源: 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

另请参阅: