Javascript 如何从 Vue.js 中的 URL 获取查询参数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35914069/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 18:22:53  来源:igfitidea点击:

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

javascriptvue.jsvue-routerurl-parameters

提问by Rob

How can I fetch query parameters in Vue.js?

如何在 Vue.js 中获取查询参数?

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

例如http://somesite.com?test=yay

Can't find a way to fetch or do I need to use pure JS or some library for this?

找不到获取的方法,还是我需要为此使用纯 JS 或某个库?

回答by Yerko Palma

According to the docs of route object, you have access to a $routeobject from your components, that expose what you need. In this case

根据route object的文档,您可以$route从组件访问一个对象,该对象公开您需要的内容。在这种情况下

//from your component
console.log(this.$route.query.test) // outputs 'yay'

回答by erajuan

Without vue-route, split the URL

不使用vue-route,拆分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:

另一个解决方案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(){
  },

回答by Sabyasachi

More detailed answer to help the newbies of VueJS:

帮助VueJS新手的更详细的答案:

  • First define your router object, select the mode you seem fit. You can declare your routes inside the routes list.
  • Next you would want your main app to know router exists, so declare it inside the main app declaration .
  • Lastly they $route instance holds all the information about the current route. The code will console log just the parameter passed in the url. (*Mounted is similar to document.ready , .ie its called as soon as the app is ready)
  • 首先定义你的路由器对象,选择你认为合适的模式。您可以在路线列表中声明您的路线。
  • 接下来,您希望您的主应用程序知道路由器存在,因此在主应用程序声明中声明它。
  • 最后,它们 $route 实例保存有关当前路线的所有信息。该代码将仅记录在 url 中传递的参数。(*Mounted 类似于 document.ready ,即一旦应用程序准备好就调用它)

And the code itself:

和代码本身:

<script src="https://unpkg.com/vue-router"></script>
var router = new VueRouter({
    mode: 'history',
    routes: []
});
var vm =  new Vue({
    router,
    el: '#app',
    mounted: function() {
        q = this.$route.query.q
        console.log(q)
    },
});

回答by Mike P

Another way (assuming you are using vue-router), is to map the query param to a prop in your router. Then you can treat it like any other prop in your component code. For example, add this route;

另一种方法(假设您正在使用vue-router)是将查询参数映射到路由器中的道具。然后你可以像对待组件代码中的任何其他 prop 一样对待它。比如添加这条路由;

{ 
    path: '/mypage', 
    name: 'mypage', 
    component: MyPage, 
    props: (route) => ({ foo: route.query.foo })  
}

Then in your component you can add the prop as normal;

然后在您的组件中,您可以正常添加道具;

props: {
    foo: {
        type: String,
        default: null
    }
},

Then it will be available as this.fooand you can do anything you want with it (like set a watcher, etc.)

然后它将可用this.foo,你可以用它做任何你想做的事情(比如设置一个观察者等)

回答by Marco

As of this date, the correct way according to the dynamic routing docsis:

截至目前,根据动态路由文档的正确方法是:

this.$route.params.yourProperty

instead of

代替

this.$route.query.yourProperty

回答by roli roli

You can use vue-router.I have an example below:

你可以使用 vue-router。我在下面有一个例子:

url:www.example.com?name=john&lastName=doe

网址:www.example.com?name=john&lastName=doe

new Vue({
  el: "#app",
  data: {
    name: '',
    lastName: ''
  },
  beforeRouteEnter(to, from, next) {
      if(Object.keys(to.query).length !== 0) { //if the url has query (?query)
        next(vm => {
         vm.name = to.query.name
         vm.lastName = to.query.lastName
       })
    }
    next()
  }
})

Note:In beforeRouteEnterfunction we cannot access the component's properties like: this.propertyName.That's why i have pass the vmto nextfunction.It is the recommented way to access the vue instance.Actually the vmit stands for vue instance

注意:beforeRouteEnter函数中,我们无法访问组件的属性,例如:this.propertyName.这就是我将vmtonext函数传递给函数的原因。这是访问 vue 实例的推荐方式。vm实际上,它代表 vue 实例

回答by revati raman

You can get By Using this function.

您可以通过使用此功能来获取。

console.log(this.$route.query.test)

回答by trishke

If your url looks something like this:

如果您的网址如下所示:

somesite.com/something/123

Where '123' is a parameter named 'id' (url like /something/:id), try with:

其中 '123' 是一个名为 'id' 的参数(网址如 /something/:id),请尝试:

this.$route.params.id

回答by Cao Shouguang

If your server uses php, you can do this:

如果您的服务器使用 php,您可以这样做:

const from = '<?php echo $_GET["from"];?>';

Just works.

只是工作。