具有一个路由器组件和一个菜单的动态Vue路由

时间:2019-09-18 12:28:48

标签: javascript vue.js vue-router

在我的Vue项目中,我想在我的router.js中有嵌套的路由,并且只为所有嵌套的路由提供一个菜单,在主组件中也有一个<router-view></router-view>

所以我想要这个(伪代码)

<master>

  <menu>
  </menu>

  <router-view>    
  </router-view>

</master>

在我的router.js中,

{ 
  path: '/master',
  name: 'master',
  component: Master,
  children:[
    {
      path: ':team',
      name: 'team',
      component: Team,
      children:[
        {
          path: ':group',
          name: 'group',
          component: Group,
          children:[
            {path: ':one',
            name: 'one',
            component: One}
          ]
        }
      ]
    }
  ]
}

在我的Master.vue中,我有

<template>
  <div>

        <router-link class="link" :to="{name:'team', params: {team: 'ta'}}">team a</router-link> 
        <router-link class="link" :to="{name:'team', params: {team: 'tb'}}">team b</router-link> 
        <router-link class="link" :to="{name:'group', params: {group: 'ga'}}">group a</router-link> 
        <router-link class="link" :to="{name:'group', params: {group: 'gb'}}">group b</router-link> 
        <router-link class="link" :to="{name:'one', params: {one: 'oa'}}">one a</router-link>  
        <router-link class="link" :to="{name:'one', params: {one: 'ob'}}">one b</router-link>    

      <router-view></router-view>
  </div>
</template>

<script>   
    export default {
        name: "Master"
    }
</script>  

这无法正常工作。如果我单击b组,然后转到一个组,则该URL变为ta/ga,它应为tb/ga

编辑,我也收到这些警告

[vue-router] Duplicate named routes definition: { name: "team", path: "/master/:team" }
[vue-router] Duplicate named routes definition: { name: "group", path: "/master/:team/:group" }
[vue-router] Duplicate named routes definition: { name: "one", path: "/master/:team/:group/:one" }
[vue-router] Duplicate named routes definition: { name: "master", path: "/master" }
[vue-router] missing param for named route "group": Expected "team" to be defined
[vue-router] missing param for named route "one": Expected "team" to be defined

我可以删除嵌套的路线,但是随后我的所有路线都像path: ':team/:group/:one'一样,我不知道它是否正确而且不太优雅。

我怎样才能两全其美?嵌套路线和一个菜单/一个路由器?可能吗?

谢谢

1 个答案:

答案 0 :(得分:1)

在分组的情况下,您必须添加团队参数,如果您单击TEAM B,则发送一个参数(TB),然后,如果您单击GROUP A,则仅发送参数GA,而丢弃您提供的信息, TB”。 解决方案:您可以在嵌套的路由器链接中使用$ route.params.id,该链接仅在您选择团队时出现,然后您可以这样做:

 <router-link class="link" :to="{name:'group', params: {group: 'ga', team: $route.params.team}}">group a</router-link> 
        <router-link class="link" :to="{name:'group', params: {group: 'gb', $route.params.team}}">group b</router-link>

您还可以将其添加到代码中,并且仅在用户输入团队时才激活组链接(必须先单击一个团队,然后他们才能单击组)