[Vuejs]-Vue-router and dynamic routes: not working

1👍

Here a working example doing the navigation with Programmatic and Declarative ways, check if you are missing something.

Also if you do the navigation via JS, in order to pass the params to the router.push(), you need to ref the component via name prop, not the path

const Test = {
  template: `<div> {{ $route.params.name }}</div>`
}

const router = new VueRouter({
  routes: [
    { path: '/test/:name', component: Test, name:'test' }
  ]
})

const app = new Vue({
  router,
  methods: {
    fromJS () {
      this._router.push({ name: 'test', params: { name: 'doe' }})
    }
  }
 }).$mount('#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">
  <p>
    <router-link to="/test/john">John</router-link>
    <router-link to="/test/doe">Doe</router-link>
    <button @click="fromJS">To doe from JS</button>
  </p>
  <router-view></router-view>
</div>
👤DobleL

1👍

Sorry, it was my mistake. I got the next snippet in the bottom of router js file:

router.beforeEach((to, from, next) => {
  router.options.routes.forEach((value, key) => {
    if (value.path.localeCompare(to.path) === 0) {
      if (value.secure === false || store.getters.getLogInStatus === true) {
        next()
      } else if (value.secure === true && store.getters.getLogInStatus === false) {
        router.push({
          'name': 'Login'
        })
      }
    }
  })
})

Here the third line is where mistake happens because /test/:name is not match /test/anyname.

👤Clark

Leave a comment