【发布时间】:2021-09-29 15:39:27
【问题描述】:
今天尝试使用Vue-Router(在Vue-CLI中)获取URL参数时遇到困难($route.query为空),代码如下。
代码用途:获取URL后面携带的参数(如“http://localhost:8080/#/?client_id=00000000000077”中的client_id)
【问题讨论】:
标签: vue.js vue-router vuejs3
今天尝试使用Vue-Router(在Vue-CLI中)获取URL参数时遇到困难($route.query为空),代码如下。
代码用途:获取URL后面携带的参数(如“http://localhost:8080/#/?client_id=00000000000077”中的client_id)
【问题讨论】:
标签: vue.js vue-router vuejs3
我不确定为什么 $router.currentRoute 和 $route 不匹配,但如果您需要在 mounted() 中使用 $router.currentRoute.query.client_id,您可以简单地使用它。
另一种解决方法是在$route.query.client_id 上使用$watch:
export default {
mounted() {
const unwatch = this.$watch('$route.query.client_id', clientId => {
console.log({ clientId })
// no need to continue watching
unwatch()
})
}
}
或组合 API 中的 watch:
import { watch } from 'vue'
import { useRoute } from 'vue-router'
export default {
mounted() {
console.log({
route: this.$route,
router: this.$router,
})
},
setup() {
const route = useRoute()
const unwatch = watch(() => route.query.client_id, clientId => {
console.log({ clientId })
// no need to continue watching
unwatch()
})
}
}
【讨论】: