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

Vue Router:如何调整路由路径以提取纯数字路由参数?

解决路由参数仅提取纯数字的问题

方案一:修改路由路径直接实现

把原路由路径替换为:

/custom/:length(\d+)?(?:-letter-)?words

(注:部分路由库如Vue Router需要转义反斜杠,写成/custom/:length(\\d+)?(?:-letter-)?words)

原理:

  • :length(\d+)?:将length参数的正则限定为纯数字\d+,末尾的?让该参数可选
  • (?:-letter-)?:用非捕获分组匹配可选的-letter-字符串,这部分不会被纳入length参数
  • 匹配效果:
    • 访问/custom/3-letter-words时,this.$route.params.length返回3
    • 访问/custom/words时,this.$route.params.length为undefined,仍能正常匹配路径

方案二:参数后处理(无需修改路由)

如果路由库不支持复杂正则分组,可在获取参数时提取纯数字:

const rawLength = this.$route.params.length;
const pureLength = rawLength ? rawLength.match(/\d+/)[0] : undefined;

通过正则\d+从原始参数中提取纯数字部分,同样能达到需求。

内容的提问来源于stack exchange,提问作者Süleyman Gezsat

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 01:25:23