【问题标题】:vue router /:param with slashesvue 路由器/:带斜杠的参数
【发布时间】:2019-05-22 06:07:49
【问题描述】:

我有一个这样的路由器:

routes: [
    {
      path: '/survey/:surveyHash',
      name: 'survey',
      component: Survey,
      props: true,
    },

在组件中,我试图在道具中获取surveyHash。问题是当surveyHash 里面有/ 斜线时我做不到。

vue-router 有解决方案吗?

【问题讨论】:

  • 使用encodeURIComponent encodeURIComponent('cat/abc') -> cat%2Fabc
  • 但是怎么做呢?这个encodeURIComponent 放在哪里?
  • 无论您在何处生成 URL,都需要对其进行编码
  • 好的,所以我需要和后端开发人员谈谈;P

标签: javascript vue.js vue-component vue-router


【解决方案1】:

您可以在路由定义中使用custom matching pattern

routes: [
    {
      path: '/survey/:surveyHash(.*)',
      name: 'survey',
      component: Survey,
      props: true,
    },

这样您将获得 URL 的其余部分,包括 surveyHash 中的斜线

【讨论】:

  • @AdamOrlov 请记住,这将匹配之后的所有内容,这意味着您不能使用 /survey/{hash}/edit 例如
  • 谢谢 Derek,好点,但在我的情况下,这非常有效。
【解决方案2】:

还有更优雅的解决方案。 Vue 路由器在底层使用了 path-to-regexp 模块,它提供了开箱即用的解决方案

const regexp = pathToRegexp('/:foo*')
// keys = [{ name: 'foo', delimiter: '/', optional: true, repeat: true }]

https://github.com/pillarjs/path-to-regexp#zero-or-more

const regexp = pathToRegexp('/:foo+')
// keys = [{ name: 'foo', delimiter: '/', optional: false, repeat: true }]

https://github.com/pillarjs/path-to-regexp#one-or-more

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-09-07
    • 2011-03-23
    • 2013-05-25
    • 1970-01-01
    • 2011-05-15
    • 2020-05-29
    • 1970-01-01
    • 2018-10-28
    相关资源
    最近更新 更多