How can I get query parameters from a URL in Vue.js?

后端 未结 9 1486
甜味超标
甜味超标 2020-12-12 13:47

How can I fetch query parameters in Vue.js?

E.g. http://somesite.com?test=yay.

Can’t find a way to fetch or do I need to use pure JS or some lib

9条回答
  •  伪装坚强ぢ
    2020-12-12 14:48

    Without vue-route, split the URL

    var vm = new Vue({
      ....
      created()
      {
        let uri = window.location.href.split('?');
        if (uri.length == 2)
        {
          let vars = uri[1].split('&');
          let getVars = {};
          let tmp = '';
          vars.forEach(function(v){
            tmp = v.split('=');
            if(tmp.length == 2)
            getVars[tmp[0]] = tmp[1];
          });
          console.log(getVars);
          // do 
        }
      },
      updated(){
      },
    

    Another solution https://developer.mozilla.org/en-US/docs/Web/API/HTMLHyperlinkElementUtils/search:

    var vm = new Vue({
      ....
      created()
      {
        let uri = window.location.search.substring(1); 
        let params = new URLSearchParams(uri);
        console.log(params.get("var_name"));
      },
      updated(){
      },
    

提交回复
热议问题