Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

(Vue.js) Same component with different routes

Tags:

I would like to use the same component for different routes in a Vue.js application.

I currently have something like this:


main.js

const routes = [     { path: '/route-1', name: 'route-1', component: MyComponent },     { path: '/route-2', name: 'route-2', component: MyComponent },     { path: '/route-3', name: 'route-3', component: MyComponent },  ]  const router = new VueRouter({     routes }) 

myComponent.vue

<ul>     <li><router-link to="/route-1">Route 1</router-link></li>     <li><router-link to="/route-2">Route 2</router-link></li>     <li><router-link to="/route-3">Route 3</router-link></li> </ul> 

When I type the route manually in the browser, everything is working well, but when I try to navigate between the routes using some of these router-generated-links, nothing happens. The route changes but the content is still the same. Any idea how I can solve this?

Thanks!

like image 615
Moisés Pio Avatar asked Mar 05 '17 01:03

Moisés Pio


People also ask

Can we define multiple router outlets in a component Vue?

Instead of having one single outlet in your view, you can have multiple and give each of them a name. A router-view without a name will be given default as its name.

Does Vue reuse components?

Vue components, on the other hand, are great when you want to reuse template code, aka child component, that can be used in multiple parent components. Now you have a better understanding of not only the differences but also which one to use.


1 Answers

This is expected behaviour as Vue is trying to be optimal and reuse existing components. The behaviour you want to achieve used to be solved with a setting called canReuse, but that has been deprecated. The current recommended solution is to set a unique :key property on your <router-view> like so:

<router-view :key="$route.path"></router-view> 

Check out this JSFiddle example.

like image 69
mzgajner Avatar answered Sep 22 '22 13:09

mzgajner