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

E.g.

http://somesite.com?test=yay

找不到方法来获取或我需要使用纯JS或一些库为这?


当前回答

示例:http://localhost:9528/#/course/outline/1439990638887137282

以下代码输出:1439990638887137282

this.courseId = this.$route.params.id
console.log('courseId', this.courseId)

其他回答

示例:http://localhost:9528/#/course/outline/1439990638887137282

以下代码输出:1439990638887137282

this.courseId = this.$route.params.id
console.log('courseId', this.courseId)

没有vue-router,拆分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() {
  },
....

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

试试这段代码

var vm = new Vue({
  created() {
    let urlParams = new URLSearchParams(window.location.search);
    console.log(urlParams.has('yourParam')); // true
    console.log(urlParams.get('yourParam')); // "MyParam"
  },
});

根据route object的文档,你可以从你的组件中访问$route对象,它公开了你需要什么。在这种情况下

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

有一件事要记住,如果你正在使用哈希模式,那么不要使用这个