Vue - 导航到下一个子路由

use*_*250 2 javascript vue.js vue-router vuejs2

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

我的计划是拥有多个带有子页面的父页面,以及一些通过子页面导航的导航箭头。

  {
    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
      },     
    ]
  }
Run Code Online (Sandbox Code Playgroud)

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

例如,如果我在“childPage2”上,我希望能够单击一个按钮导航到下一个孩子和上一个孩子?然后一旦在“childPage3”上,由于没有 childPage4 ,只有一个选项可以导航回去?

谢谢

Dec*_*oon 5

您可以使用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,
          },     
        ],
      },
    ],
  }),
});
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)