Vue - 导航到下一个 child 路线

Vue - Navigate to next child route

我目前已经准备好了这些路线(例如更改了名称),但在寻找在 child 页面之间导航的方法时遇到了问题。

我的计划是有多个 parent 页面和 child 页面,以及一些导航箭头,它们将在 child 页面中导航 .

  {
    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
      },     
    ]
  }

但我想知道是否有办法导航到列表中的下一个上一个child?

例如,如果我在 "childPage2",我希望能够单击一个按钮导航到下一个 child 和上一个 child?然后在 "childPage3" 上只有一个选项可以返回,因为没有 childPage4 ?

谢谢

您可以使用提供给 VueRouter 构造函数的 routes 选项作为确定导航的方法:

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>