【问题标题】:(Vue.js) Same component with different routes(Vue.js)具有不同路由的相同组件
【发布时间】:2017-07-25 00:31:21
【问题描述】:

我想在 Vue.js 应用程序中为不同的路由使用相同的组件。

我目前有这样的事情:


ma​​in.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>

当我在浏览器中手动键入路由时,一切正常,但是当我尝试使用其中一些 router-generated-links 在路由之间导航时,什么也没有发生。路线变了,但内容还是一样的。知道如何解决这个问题吗?

谢谢!

【问题讨论】:

  • 嗯,您使用的是相同的组件,所以这就是为什么没有任何变化,实际上唯一变化的是路线。

标签: javascript routing vue.js


【解决方案1】:

您可以使用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();
  },
}

【讨论】:

    【解决方案2】:

    只是为了做个笔记。如果有人使用 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
    })
    

    【讨论】:

      【解决方案3】:

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

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

      看看这个JSFiddle example。

      【讨论】:

      • 像魅力一样工作!我理解这是预期行为的原因,但由于我有三个相似的页面,但只有一些内容差异,我必须使用三种不同的路线为每个页面加载正确的内容。那是我的第一个项目,也许我会找到一个更优雅的解决方案来实现相同的结果。但是,是的,谢谢! :)
      • Duuuuuuddddeeeee 我快疯了。很高兴我找到了这个答案
      猜你喜欢
      • 2018-10-16
      • 1970-01-01
      • 2019-06-11
      • 1970-01-01
      • 2019-11-17
      • 1970-01-01
      • 2021-08-23
      • 2019-06-15
      • 2018-11-04
      相关资源
      最近更新 更多