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

Moi*_*Pio 10 javascript routing vue.js

我想在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
})
Run Code Online (Sandbox Code Playgroud)

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>
Run Code Online (Sandbox Code Playgroud)

当我在浏览器中手动键入路由时,一切都运行良好,但是当我尝试使用这些路由器生成的链接之一在路由之间导航时,没有任何反应.路线改变但内容仍然相同.知道如何解决这个问题吗?

谢谢!

mzg*_*ner 24

这是预期的行为,因为Vue试图获得最佳并重用现有组件.您想要实现的行为过去通过调用的设置来解决canReuse,但已被弃用.目前推荐的解决方案是:key在您的<router-view>喜欢上设置一个独特的属性:

<router-view :key="$route.path"></router-view>
Run Code Online (Sandbox Code Playgroud)

看看这个JSFiddle示例.

  • Duuuuuuddddeeeee 我快疯了。很高兴我找到了这个答案 (4认同)
  • 奇迹般有效!我知道这是预期行为的原因,但是由于我有三个相似的页面,但内容有所不同,因此我必须使用三种不同的路由为每个页面加载正确的内容。那是我的第一个项目,也许我会找到一个更优雅的解决方案来实现相同的结果。但是,是的,谢谢!:) (2认同)

Ser*_*g_x 6

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

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

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

用户.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();
  },
}
Run Code Online (Sandbox Code Playgroud)