Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
191
rated 0 times [  198] [ 7]  / answers: 1 / hits: 24844  / 7 Years ago, sun, march 5, 2017, 12:00:00

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!


More From » routes

 Answers
27

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.


[#58680] Thursday, March 2, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
shannon

Total Points: 606
Total Questions: 106
Total Answers: 111

Location: Lesotho
Member since Thu, Jun 30, 2022
2 Years ago
;