首页 > 解决方案 > v-tabs 和 vue-router 在 Vue.js 上重用组件

问题描述

这是我的原始组件(称为'Main'),它基本上显示了由选项卡驱动的3个子组件,其中2个是相同的类型。这一切都很好:

<v-tabs v-model="tab">
    <v-tab key='scenario'>Scenario</v-tab>
    <v-tab key='primary'>Primary</v-tab>
    <v-tab key='spouse'>Spouse</v-tab>
</v-tabs>

<v-tabs-items>
    <v-tab-item key='scenario'>
        <ScenarioView></ScenarioView>
        </v-tab-item>
    <v-tab-item key='primary'>
        <CustomerView :isPrimary="true"></CustomerView>
    </v-tab-item>
    <v-tab-item key='spouse'>
        <CustomerView :isPrimary="false"></CustomerView>        
    </v-tab-item>
</v-tabs-items>

但是,标签导航的问题之一是您没有获得浏览器历史记录,因此我想使用 vue-router 添加它。通过一些谷歌搜索,我最终得到:

<v-tabs v-model="tab">
    <v-tab key='scenario' to='/main/scenario'>Scenario</tab>
    <v-tab key='primary' to='/main/primary'>Primary</v-tab>
    <v-tab key='spouse' to='/main/spouse'>Spouse</v-tab>
</v-tabs>
<router-view></router-view>

这很好用,除了看起来 CustomerView 组件正在被重用,我没有得到单独的组件。我认为这是预期的行为。

我的片段router/index.js

// ...
path: '/main',
name: 'Main',
component: Main,
children: [
    {
      path: 'scenario',
      component: ScenarioView
    },
    {
      path: 'primary',
      component: CustomerView,
      props: { isPrimary: true }
    },
    {
      path: 'spouse',
      component: CustomerView,
      props: { isPrimary: false }
    },
  ]

那么,有没有办法不让 vue-router 重用组件?或者有没有更好的方法来添加 vue-router 导航到 vuetify v-tabs?

谢谢。

标签: vue.jstabsvue-router

解决方案


添加:key<router-view>

<v-tabs v-model="tab">
    <v-tab key='scenario' to='/main/scenario'>Scenario</tab>
    <v-tab key='primary' to='/main/primary'>Primary</v-tab>
    <v-tab key='spouse' to='/main/spouse'>Spouse</v-tab>
</v-tabs>
<router-view :key="$route.path"></router-view>

推荐阅读