(Vue.js) 相同组件不同路由

新手上路,请多包涵

我想在 Vue.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
})


我的组件.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>


当我在浏览器中手动输入路线时,一切正常,但当我尝试使用其中一些 路由器生成的链接 在路线之间导航时,没有任何反应。路线变了,内容还是一样。知道我该如何解决这个问题吗?

谢谢!

原文由 Moisés Pio 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 599
2 个回答

这是预期的行为,因为 Vue 正在尝试优化并重用现有组件。您想要实现的行为曾经通过名为 canReuse 的设置来解决,但已被弃用。当前推荐的解决方案是在您的 <router-view> 上设置一个独特的 :key 属性,如下所示:

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

查看此 JSFiddle 示例

原文由 mzgajner 发布,翻译遵循 CC BY-SA 3.0 许可协议

您可以使用 watch 属性,这样您的组件就不会浪费时间重新加载:

index.js 你可能有这样的东西

const routes = [
  {
    path: '/users/:id',
    component: Vue.component('user', require('./comp/user.vue').default)
  }
]

用户.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();
  },
}

原文由 Serg_x 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题