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!
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With