0

I'm a newbie in javascript and vue.js and I'm facing some issue when trying to add a new route in an existing programme.

I created my new component in a separate file called Miniature.vue

I added the new route in the router definition:

  export default new Router({
  routes: [
    {
      path: '/certificat/:id',
      name: 'Certificat',
      component: Certificat
    },
    {
      path: '/miniature/:id',
      name: 'Miniature',
      component: Miniature
    }
  ]
})

And then, in the vue instantiation, I added my new components and updated the template :

new Vue({
el: '#app',
router,
components: { Certificat, Miniature } ,
template: '<div>
            <Certificat></Certificat>
            <Miniature></Miniature>
            </div>'
})

The previous template was simply

template: '<Certificat/>'

Problem is, the url is either mywebsite/certificat/123 or mywebsite/miniature/123, both routes are executed, and my two components are displayed ! What is the purpose of the template in the Vue constructor anyway? If I remove it, nothing happens.

What am I missing here ??

2 Answers 2

0

Those components are supposed to be loaded from your route, so they shouldn't be in your app template (i.e., they should be removed from #app's components and template).

Your app should contain <router-view> somewhere for the route to be rendered. In your case, replace the app template string with <router-view/>.

It should look similar to this:

new Vue({
  el: '#app',
  router,
  template: '<router-view/>'
})

I should mention your router setup is missing a route for / and 404, so the default path and unknown routes will render nothing in your app. Users would have to navigate to the exact routes you've configured to see anything.

Sign up to request clarification or add additional context in comments.

3 Comments

This works better. Thanks for the clarification. How can I add a route for 404 ?
No problem :) For 404, use a path: '*' as the last route. Example: { path: '*', component: { template: '<div>Not found {{$route.path}}</div>' } }
Thanks @tony19 Is there a way to make different routes for different error codes ? (one for 404, one for 500...)
0

Vue doesn't have routing built-in, for routing you'll need the vue-router package.

To get a better understanding of template and Vue in general, I recommend reading the Introduction guide

1 Comment

Already read it, didn't find any answer to my problem... thanks anyway...