menu

Questions & Answers

Two Path with same route and same component - Vue js

I have two path with same component like this:

/:loc("-host") - should match /usa-host

/:loc/:sublocation("-host") - should match /usa/washington-host

how to achieve this using single named route in vue.js

Comments:
2023-01-19 23:20:02
You can use regex in vuerouter
2023-01-19 23:20:02
You could do /:loc/:sublocation? then sublocation will be optional
2023-01-19 23:20:02
You can check the documentation of path-to-regexp that is used by vue-router
Answers(2) :

You can use alias of path

const router = new VueRouter({
    routes: [
        { path: '/a', component: A, alias: '/b' }
    ]
})

Check in doc

const Home = { template: '<div>Home</div>' }
const Project = { 
    template: '<div>Project {{id}}</div>',
  mounted(){
    console.log(this.$route);
  },
  data: function () {
    return {
        id:this.$route.params.id||'',
    }
  }
}

const router = new VueRouter({
  mode: 'history',
  routes: [
  {
    path: '/',
    component: Home
  },
  {
    path: '/projects/:id?',
    component: Project,
    alias: '/project/:id'
  }
]
})

new Vue({
    router,
  el: '#app'
})
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<script src="https://unpkg.com/vue-router/dist/vue-router.js"></script>

<div id="app">
<router-link to="/">Home</router-link> |
<router-link to="/projects">projects</router-link> |
<router-link to="/project/1">project/1</router-link>
<router-view></router-view>
</div>

Also check fiddle : https://jsfiddle.net/nikleshraut/9sgk6yg4/1/

Note : Opening same component is not working by default, you need to use other trick. For just testing above fiddle, go home->/projects and home->/project/1 will work but /projects->/project/1 or /project/1->/projects will not work. To make it work do something like this : https://jsfiddle.net/nikleshraut/9sgk6yg4/

This is my solution.

Router:

Use ? to separate param from literal in route.

const router = new VueRouter({
  routes: [
    { path: '/', component: Home },
    { path: '/:loc/:subloc?-host', component: Location },
    { path: '/:loc?-host', component: Location },
  ]
})

Component:

Set local variables from $route.params.

const Location = { 
  template: '<div>Location {{loc}} - {{ subloc }}</div>',
  data: function () {
    return {
      loc: this.$route.params.loc,
      subloc: this.$route.params.subloc,
    }
  },
}

Template:

Use :key="$route.fullPath" to ensure component re-creates each navigation.

<div id="app">
  <router-link to="/">Home</router-link> |
  <router-link to="/usa-host" >loc1</router-link> |
  <router-link to="/usa/washington-host"  >loc2</router-link>
  <router-view :key="$route.fullPath"></router-view>
</div>


Fiddle here