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

E.g.

http://somesite.com?test=yay

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


当前回答

到目前为止,根据动态路由文档,正确的方式是:

this.$route.params.yourProperty

而不是

this.$route.query.yourProperty

其他回答

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

url: www.example.com ?名字= john&lastName =能源部

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();
  }
})

注意:在beforeRouteEnter函数中,我们不能访问组件的属性,例如:this.propertyName。这就是为什么我把vm传递给下一个函数。这是访问vue实例的推荐方式。实际上,vm代表vue实例

到目前为止,根据动态路由文档,正确的方式是:

this.$route.params.yourProperty

而不是

this.$route.query.yourProperty

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

以下代码输出:1439990638887137282

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

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

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

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

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

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

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

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