Home > other >  Vue-router - How to add custom suffix to route param?
Vue-router - How to add custom suffix to route param?

Time:09-08

I have this route path

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

It matches below routes as expected ✅

/custom/3-letter-words
/custom/words

However, this.$route.params.length returns 3-letter-.

My expectation is that this.$route.params.length will return 3 as a result and the route path I entered will match both routes above.

In this case, how should I change the route path above? If you think that it won't work by changing the route path, do you have any other suggestions?

CodePudding user response:

You could try

 path: "/custom/:length(\\d )?-letter-words",
 alias: "/custom/words"

which would output the correct value for length, but this would also match /custom/-letter-words.

Unfortunately you can't use :length(?:(\\d )-letter-)? with vue-router, it doesn't parse it correctly.

Another option would be to use props in function mode:

props: (route) => ({
        letterCount: route.params.length ?
          route.params.length.match(/^\d /)[0] :
          null
      })

CodePudding user response:

Vue-router uses path-to-regexp library for path matching and this library actually supports custom prefix and suffix: https://github.com/pillarjs/path-to-regexp#custom-prefix-and-suffix

The problem here is that the version of this library that vue-router uses is old (v1.8.0) and this feature is not supported in this version. There is an opened issue on vue-router about this, but they said they won't do it because there is a breaking change in the new version.

So it seems that it is not possible to do this by structuring the path. Since the best practice method cannot be applied, of course, there may be different alternative ideas, but I personally prefer to get the variable while parsing the route.param.

  • Related