代码之家  ›  专栏  ›  技术社区  ›  user3195250

Vue-导航到下一个子路由

  •  2
  • user3195250  · 技术社区  · 6 年前

    只有

      {
        path: '/parentPage',
        name: 'parentPage',
        component: parentPage
        children: [
          {
            path: 'childPage1',
            name: 'childPage1',
            component: childPage1
          },
          {
            path: 'childPage2',
            name: 'childPage2',
            component: childPage2
          },
          {
            path: 'childPage3',
            name: 'childPage3',
            component: childPage3
          },     
        ]
      }
    

    下一个 名单上的孩子?

    1 回复  |  直到 6 年前
        1
  •  4
  •   Decade Moon    6 年前

    您可以使用 routes VueRouter

    const parentPage = {
      template: `
        <div>
          <nav>
            <router-link v-if="prev" :to="prev">Prev</router-link>
            <router-link v-if="next" :to="next">Next</router-link>
          </nav>
          <router-view/>
        </div>
      `,
      computed: {
        routes() {
          return this.$router.options.routes.find(r => r.name === 'parentPage').children;
        },
        routeIndex() {
          return this.routes.findIndex(r => r.name === this.$route.name);
        },
        prev() {
          const route = this.routes[this.routeIndex - 1];
          return route && { name: route.name };
        },
        next() {
          const route = this.routes[this.routeIndex + 1];
          return route && { name: route.name };
        },
      },
    };
    
    const childPage1 = { template: '<div>childPage1</div>' };
    const childPage2 = { template: '<div>childPage2</div>' };
    const childPage3 = { template: '<div>childPage3</div>' };
    
    new Vue({
      el: '#app',
      router: new VueRouter({
        routes: [
          {
            path: '/parentPage',
            name: 'parentPage',
            component: parentPage,
            children: [
              {
                path: 'childPage1',
                name: 'childPage1',
                component: childPage1,
              },
              {
                path: 'childPage2',
                name: 'childPage2',
                component: childPage2,
              },
              {
                path: 'childPage3',
                name: 'childPage3',
                component: childPage3,
              },     
            ],
          },
        ],
      }),
    });
    <script src="https://rawgit.com/vuejs/vue/dev/dist/vue.js"></script>
    <script src="https://rawgit.com/vuejs/vue-router/dev/dist/vue-router.js"></script>
    
    <div id="app">
      <router-link to="/parentPage/childPage1">/parentPage/childPage1</router-link>
      <router-view></router-view>
    </div>