如何在Vue.js中获取查询参数?
E.g.
http://somesite.com?test=yay
找不到方法来获取或我需要使用纯JS或一些库为这?
如何在Vue.js中获取查询参数?
E.g.
http://somesite.com?test=yay
找不到方法来获取或我需要使用纯JS或一些库为这?
当前回答
到目前为止,根据动态路由文档,正确的方式是:
this.$route.params.yourProperty
而不是
this.$route.query.yourProperty
其他回答
另一种方法(假设您使用vue-router)是将查询参数映射到路由器中的道具。然后,您可以像对待组件代码中的其他道具一样对待它。例如,添加此路由;
{
path: '/mypage',
name: 'mypage',
component: MyPage,
props: (route) => ({ foo: route.query.foo }),
}
然后在你的组件中,你可以像往常一样添加道具;
props: {
foo: {
type: String,
default: null,
}
},
那么它将以这样的形式出现。Foo,你可以做任何你想做的(像设置一个观察者,等)。
根据route object的文档,你可以从你的组件中访问$route对象,它公开了你需要什么。在这种情况下
//from your component
console.log(this.$route.query.test) // outputs 'yay'
下面是如何做到这一点,如果你正在使用vue-router与ve3组合api
import { useRoute } from 'vue-router'
export default {
setup() {
const route = useRoute()
console.log(route.query)
}
}
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
试试这段代码
var vm = new Vue({
created() {
let urlParams = new URLSearchParams(window.location.search);
console.log(urlParams.has('yourParam')); // true
console.log(urlParams.get('yourParam')); // "MyParam"
},
});