【问题标题】:Access the query string in VueJS访问 VueJS 中的查询字符串
【发布时间】:2018-03-05 13:56:11
【问题描述】:

我刚刚开始使用 VueJS,我真的很喜欢它! :) 我想将查询字符串中的值保存到 VueJS 变量中——这在把手 + 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,但我不确定这是否真的是我需要的/如何使用它。我目前正在使用 express 来处理我的后端逻辑/路由。

谢谢,

奥莉

【问题讨论】:

标签: html express url vue.js vue-router


【解决方案1】:

您可以将所有参数放入 url 的哈希中,例如:

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

它会改变你的网址——#之后的部分

或者,如果您坚持使用Change URL parameters 中的一种解决方案将它们作为查询参数(? 之后发生的事情)

【讨论】:

    【解决方案2】:

    您可以使用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

    另请参阅:
    https://stackoverflow.com/a/12151322/194717

    【讨论】:

      猜你喜欢
      • 2012-02-16
      • 1970-01-01
      • 1970-01-01
      • 2012-08-19
      • 1970-01-01
      • 1970-01-01
      • 2014-09-04
      • 1970-01-01
      • 2013-07-06
      相关资源
      最近更新 更多