Vue Router中如何获取URL参数?$router无params对象
获取URL参数的几种解决方案
首先要明确:$router是路由实例对象,负责路由跳转等操作,$route才是当前页面的路由信息对象,包含params、query等参数,你应该用$route来获取参数。
以下是几种可行的实现方式:
- 若你配置的是动态路由(比如路由规则为
/page/:id),直接通过$route.params获取:
mounted(){ const paramValue = this.$route.params.id; console.log(paramValue); }
- 若URL参数是查询字符串形式(比如
/page?id=123),通过$route.query获取:
mounted(){ const paramValue = this.$route.query.id; console.log(paramValue); }
- 如果上述Vue路由方式无法使用,用原生JS直接解析URL:
- 获取查询字符串参数:
mounted(){ const urlParams = new URLSearchParams(window.location.search); const paramValue = urlParams.get('id'); console.log(paramValue); }- 获取路径中的动态参数(比如
/page/123):
mounted(){ const pathParts = window.location.pathname.split('/'); // 取路径最后一段作为参数 const paramValue = pathParts[pathParts.length - 1]; console.log(paramValue); }
内容的提问来源于stack exchange,提问作者gowoo
相关产品推荐
相关产品推荐

