我希望在Vue.js应用程序中为不同的路由使用相同的组件。
我现在有这样的事情:
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>当我在浏览器中手动输入路由时,一切正常,但是当我尝试使用这些路由器生成的链接在路由之间导航时,什么都不会发生。路由改变了,但内容仍然相同。知道我怎么解决这个问题吗?
谢谢!
发布于 2017-03-05 16:30:18
这是预期的行为,因为Vue正在尝试优化和重用现有组件。您想要实现的行为过去是通过一个名为canReuse的设置来解决的,但是已经被取消了。当前推荐的解决方案是在您的:key上设置一个惟一的<router-view>属性,如下所示:
<router-view :key="$route.path"></router-view>看看这个JSFiddle实例。
发布于 2019-10-17 16:27:55
您可以使用watch属性,这样您的组件就不会浪费时间重新加载:
index.js你可能有这样的东西
const routes = [
{
path: '/users/:id',
component: Vue.component('user', require('./comp/user.vue').default)
}
]user.vue
created(){
// will fire on component first init
this.init_component();
},
watch: {
// will fire on route changes
//'$route.params.id': function(val, oldVal){ // Same
'$route.path': function(val, oldVal){
console.log(this.$route.params.id);
this.init_component();
}
},
methods: {
init_component: function(){
// do anything you need
this.load_user_data_with_ajax();
},
}发布于 2018-05-30 08:39:53
只是想做个笔记。如果有人在使用SSR模板,情况就会有所不同。@mzgajner的答案确实重新创建了组件,但不会再次触发asyncData。
要做到这一点,请像这样修改entry-client.js。
旧:
const activated = matched.filter((c, i) => {
return diffed || (diffed = (prevMatched[i] !== c))
})新的:
const activated = matched.filter((c, i) => {
/*
In my case I only needed this for 1 component
*/
diffed = ((prevMatched[i] !== c) || c.name == 'p-page-property-map')
return diffed
})https://stackoverflow.com/questions/42603583
复制相似问题