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

火爆浪子
  • 2.8k
{
    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吗?有更好作法?
回复
阅读 410
2 个回答

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

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
        }]
    },
]
宣传栏