(Vue.js)具有不同路线的相同组件 [英] (Vue.js) Same component with different routes
问题描述
我想在Vue.js应用程序中为不同的路由使用相同的组件。
I would like to use the same component for different routes in a Vue.js application.
我目前有这样的东西:
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
})
< hr>
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>
当我在浏览器中手动输入路线时,一切工作正常,但是当我尝试使用其中一些 router-generated-links 在路线之间导航时,什么也没发生。路由发生变化,但是内容仍然相同。知道我该如何解决吗?
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?
谢谢!
推荐答案
这是预期的行为,因为Vue试图做到最佳并重用现有组件。您想要实现的行为以前可以通过名为 canReuse
的设置解决,但已弃用。当前推荐的解决方案是在< router-view>
上设置唯一的:key
属性,如下所示:
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>
查看此 JSFiddle示例。
这篇关于(Vue.js)具有不同路线的相同组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!