Create a dynamic route param in Vue Router that removes spaces

I have a bunch of boxes in my app that route to a page where you can see all of the items that are in the box. As it stands my dynamic route in the index.js file looks like this:

  path: '/box/:idBox',
  name: 'ItemListByBox',
  component: ItemListByBox,

All of my boxIDs (idBox) are all strings such as Box 1, Box 2, etc.

Everything works totally fine and routes you to the right page, but the page address at the top winds up looking like http://localhost:8080/box/Box%202

Is there a way to have the address look like Box-2?



You can use a computed to transform the user input (mentioned in comments) so that spaces are replaced with dashes. You don’t need to change your route configuration.

Imagine you have a data variable that gets modified by user input called boxID and may contain spaces. Pass the computed as the route param like this:

<router-link :to="{ name: 'ItemListByBox', params: { idBox: boxFormatted }}">
export default {
  data: () => ({
    boxID: 'Box 1'
  computed: {
    boxFormatted() {
      return this.boxID.replace(/s+/g, '-')

Leave a Reply

Your email address will not be published. Required fields are marked *