vue router 第一层path的预设页面思路?

{
    name: 'aaa',
    meta: {
      title: 'aaa',
    },
    path: '/aaa',
    component: Layout,
    children: [
      {
        path: 'bbb',
        name: 'bbb',
        component: () => import('@/views/bbb'),
        meta: {
          title: 'bbb',
        },
      },
    ]
  },

/aaa/bbb 没问题
/aaa 因为没有 children 所以会是空白的
我想要做的是预设自带下面的 children 直接前往该页

Layout

watch: {
    $route(to, from) {
      this.routers.forEach((res) => {
        if (to.path === res.path) {
          this.routes = res;
          this.to = to.path;
        }
      });
    },
  },
<el-link
        v-for="(item, index) in routes.children"
        @click="HandleTo(item)"
        :key="index"
        >{{ item.meta.title }}</el-link
      >

只是我卡死了
就是每个页面都会出现 el-link (当然

  1. 我的思路是判断 path 有几层,path只有一层级就不展示 el-link,但万一日后可能会只有一层?就不灵活了
  2. 这样每一页都会监听 $route 这样ok吗?有更好作法?
阅读 2.2k
2 个回答
const routes = [{
        path: '/',
        name: 'home',
        component: Home
    },
    {
        path: '/profile',
        name: 'profile',
        component: Profile
    },
    {
        path: '/aaa',
        name: 'AAA',
        redirect: function (to) {
            const matchPath = to.matched[0].path
            if (matchPath) {
                const firstChildrenPath = routes.find(o => o.path === matchPath).children[0].path
                return `${matchPath}/${firstChildrenPath}`
            }
            return matchPath
        },
        component: AAA,
        children: [{
            path: 'bbb',
            name: 'BBB',
            component: BBB
        }]
    },
]

router上面加个redirect指向一个二级router就行了

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