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

E.g.

http://somesite.com?test=yay

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


当前回答

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

somesite.com/something/123

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

this.$route.params.id

其他回答

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

以下代码输出:1439990638887137282

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

你可以使用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

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

Vue 3组合API

(截至2021年,vue-router 4)

import {useRoute} from "vue-router";

//can use only in setup()
useRoute().query.test

or

//somewhere in your src files
import router from "~/router";

//can use everywhere 
router.currentRoute.value.query.test  

or

import {useRouter} from "vue-router";

//can use only in setup()
useRouter().currentRoute.value.query.test