Vue-router: Charater `/` is escaped in URI

Created on 24 May 2017  路  4Comments  路  Source: vuejs/vue-router

Version

2.5.3

Reproduction link

https://github.com/imcvampire/router-uri-bug

Steps to reproduce

  1. Go to http://localhost:8080/viet-nam/ha-noi
  2. Click Go to Foo
  3. See URL

What is expected?

http://localhost:8080/viet-nam/ha-noi/foo

What is actually happening?

http://localhost:8080/viet-nam%2Fha-noi/foo


Personally, I think / in path should not be escaped

Most helpful comment

It would be nice if the vue-router documentation mentioned this param field array-to-slash-delimited-string behavior.

Also, it is probably obvious, but your values for this.$route.params will be arrays instead of strings. For example, directly hitting the route (first load in a browser)
/categories/a/b will have params: {id: 'a/b'}, and then using vue-router to navigate to, say, c/d using the array method will have params: {id: ['c', 'd']}. This can be overlooked in functions where you are expecting certain type values when reading this.$route.params, so be careful.

All 4 comments

Unfortunately, / being the delimiter for paths, we must escape it when passed as a param. However, you can manually build the url and that won't be escaped:

<router-link :to="`/path/${subPath}`">

I see you're using path+, passing an array for the params should work as well: http://jsfiddle.net/posva/ncfshrwc/

For anyone stumbling upon this issue, @posva's comment to use an Array is the correct solution 馃檹 When using path* or path+, instead of passing a String to the argument, just pass in an Array of the individual items split by /.

For example, if your route looks like this:

{
  path: '/categories/:id+',
  name: 'categories-show'
}

Then to generate the clean un-escaped link use this for your template:

<router-link :to="{ name: 'categories-show', params: { id: ['foo', 'baz'] } }"><router-link/>

It would be nice if the vue-router documentation mentioned this param field array-to-slash-delimited-string behavior.

Also, it is probably obvious, but your values for this.$route.params will be arrays instead of strings. For example, directly hitting the route (first load in a browser)
/categories/a/b will have params: {id: 'a/b'}, and then using vue-router to navigate to, say, c/d using the array method will have params: {id: ['c', 'd']}. This can be overlooked in functions where you are expecting certain type values when reading this.$route.params, so be careful.

Was this page helpful?
0 / 5 - 0 ratings