You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.29 11:02:36