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

E.g.

http://somesite.com?test=yay

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


当前回答

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

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

然后在你的组件中,你可以像往常一样添加道具;

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

那么它将以这样的形式出现。Foo,你可以做任何你想做的(像设置一个观察者,等)。

其他回答

如果你的url看起来像这样:

somesite.com/something/123

其中'123'是一个名为'id'的参数(url类似/something/:id),尝试使用:

this.$route.params.id

试试这段代码

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

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

以下代码输出:1439990638887137282

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

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

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

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

然后在你的组件中,你可以像往常一样添加道具;

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

那么它将以这样的形式出现。Foo,你可以做任何你想做的(像设置一个观察者,等)。