简体   繁体   English

如何在 JavaScript 中获取 URL 参数?

[英]How to get URL parameters in JavaScript?

I'm using Vue, but I'm not using vue-router .我正在使用 Vue,但我没有使用 vue-router

How can I get URI parameters?如何获取 URI 参数?

I found one way to get URI by using root el property.我找到了一种使用 root el 属性获取 URI 的方法。

截屏

But is there any proper way to get the parameters as I want to send them to backend and get a response from server and display it.但是有没有什么正确的方法来获取参数,因为我想将它们发送到后端并从服务器获取响应并显示它。

Since you are not using vue-router , I don't think you'll be able to access your params.由于您没有使用vue-router ,我认为您无法访问您的参数。 So your only chance is to use the URL api as:因此,您唯一的机会是将 URL api 用作:

const URL = new URL(window.location.href); 
const getParam = URL.searchParams.get('foo'); 

This will give you the value of foo in ?foo=bar这会给你 foo 在?foo=bar


Alternatively, you can do something like this.或者,你可以做这样的事情。

new Vue({
 el: '#app',

 data () {
   return {
     params: window.location.href.substr(window.location.href.indexOf('?'))
   }
 },

 methods: {
   getParam (p) {
     let param = new URLSearchParams(this.params);
     if(param.has(p)){
       return param.get(p)
     }else{
       false
     }
   }
 },
})

Now, just get the param using getParam('foo')现在,只需使用getParam('foo')获取参数

You can get the URL parameters by using window.location.search:您可以使用 window.location.search 获取 URL 参数:

 const queryString = window.location.search; console.log(queryString); // ?product=troussers&color=black&newuser&size=s

For parsing parameters of the query string, use URLSearchParams:对于查询字符串的解析参数,使用 URLSearchParams:

 const urlParams = new URLSearchParams(queryString);

For more info, read this tutorial .有关更多信息,请阅读本教程

We don't use vue router for the moment either.我们暂时也不使用 vue 路由器。 We use the following script to parse args.我们使用以下脚本来解析 args。

    var args = {};

    var argString = window.location.hash;
    //everything after src belongs as part of the url, not to be parsed
    var argsAndSrc = argString.split(/src=/);
    args["src"] = argsAndSrc[1];
    //everything before src is args for this page.
    var argArray = argsAndSrc[0].split("?");
    for (var i = 0; i < argArray.length; i++) {
        var nameVal = argArray[i].split("=");
        //strip the hash
        if (i == 0) {
            var name = nameVal[0];
            nameVal[0] = name.slice(1);
        }
        args[nameVal[0]] = decodeURI(nameVal[1]);
    } 

Route properties are present in this.$route .路由属性存在于this.$route

this.$router is the instance of router object which gives the configuration of the router. this.$router是路由器对象的实例,它给出了路由器的配置。

You can get the current route query using this.$route.query您可以使用 this.$route.query 获取当前路线查询

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM