Clark
Clark

Reputation: 2213

Vue-router and dynamic routes: not working

I am using the next route:

{
  path: '/test/:name',
  name: 'Test',
  component: Test,
  // props: true,
  secure: false
}

When I'm trying to access the route http://myapp/test/helloworld in the Vue extension for the Chrome I see that route is not matched. But while testing I found that route http://myapp/test/:name (yeah, with the colon and the param name) the component is loaded. The component is anonymous and simple:

let Test = { template: '<div>sd {{ $route.params.name }}</div>' }

Upvotes: 0

Views: 7013

Answers (2)

Clark
Clark

Reputation: 2213

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.

Upvotes: 1

DobleL
DobleL

Reputation: 3928

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>

Upvotes: 1

Related Questions