如何直接从组件访问 Vue 的路由数组?

How does one access Vue's routes array directly from a component?

所以我试图创建一个 "Previous Page" / "Next Page" 类型的导航结构,它使用在我的 index.js (路线)文件中定义路线的顺序来确定下一个是哪个。但是,我在弄清楚如何访问 Routes 数组时遇到了一些困难。 Here's an example of the navigation I'm trying to replicate(具有讽刺意味的是,它在 Vue 站点的路由文档中 - 页面底部的两个小 < > 箭头)。

这是我的 index.js 文件:

import Vue from 'vue';
import Router from 'vue-router';
import Home from '@/components/home/Home';
import SearchResults from '@/components/search/SearchResults';
import Vision from '@/components/who-we-are/Vision';

Vue.use(Router);

export default new Router({
  // mode: 'history',
  routes: [
    {
      path: '/',
      name: 'Home',
      component: Home,
    },
    {
      path: '/search-results',
      name: 'SearchResults',
      component: SearchResults,
    },
    {
      path: '/who-we-are/vision',
      name: 'Vision',
      component: Vision,
    },
  ],
});

html:

<a @click="foo()">Next</a>

脚本:

import Router from 'vue-router';

export default {
  name: 'home',
  methods: {
    foo() {
      console.log(this.Router.routes[0].path);
    },
  },
};

上面的代码显然不起作用,但那是我离开的地方。

重申一下,根据上面的代码,我正在尝试获取路线数组并创建一个简单的导航,按照它们列出的顺序在它们之间移动 (next/previous)。

伪代码类似于 "on click - go to route[0].path, increment by 1." "if clicked again - go to route[ 1].path, increment by 1." 等(与前面相反。)

您可以通过 this.$router.options.routes 从组件中访问您在 Router 构造函数中指定的 routes 数组。

但是,将此对象用于显示和导航目的是完成简单任务的迂回方式。按照您想导航到它们的顺序将路由名称数组添加到您的组件会更容易:

data() {
  return {
    routeNames: ['Home', 'Search Results', 'Vision'],
  }
}

然后根据当前路由的名称创建一个方法去下一条路由:

methods: {
  goToNextRoute() {
    let index = this.routeNames.indexOf(this.$route.name);

    if (this.routeNames[index + 1]) {
      this.$router.push({ name: this.routeNames[index + 1] });
    }
  }
}

如果您真的想使用您在 Router 中定义的路线,我建议您创建一个计算 属性 来跟踪当前路线的索引。

要查找当前路线的索引,您可以这样做:

computed: {
  routeIndex() {
    let routes = this.$router.options.routes
    let index;
    for (let i = 0; i < routes.length; i++) {
      if (routes[i].name == this.$route.name) {
        index = i;
        break;
      }
    }

    return index;
  }
}

然后,转到数组中的下一条路线:

methods: {
  goToNextRoute() {
    let nextRoute = this.$router.options.routes[this.routeIndex + 1];

    this.$router.push({ name: nextRoute.name });
  }
}

我想你应该看看这个例子。

    import Vue from 'vue'
import VueRouter from 'vue-router'

// 1. Use plugin.
// This installs <router-view> and <router-link>,
// and injects $router and $route to all router-enabled child components
Vue.use(VueRouter)

// 2. Define route components
const Home = { template: '<div>home</div>' }
const Foo = { template: '<div>foo</div>' }
const Bar = { template: '<div>bar</div>' }

// 3. Create the router
const router = new VueRouter({
  mode: 'history',
  base: __dirname,
  routes: [
    { path: '/', component: Home },
    { path: '/foo', component: Foo },
    { path: '/bar', component: Bar }
  ]
})

// 4. Create and mount root instance.
// Make sure to inject the router.
// Route components will be rendered inside <router-view>.
new Vue({
  router,
  template: `
    <div id="app">
      <h1>Basic</h1>
      <ul>
        <li><router-link to="/">/</router-link></li>
        <li><router-link to="/foo">/foo</router-link></li>
        <li><router-link to="/bar">/bar</router-link></li>
        <router-link tag="li" to="/bar" :event="['mousedown', 'touchstart']">
          <a>/bar</a>
        </router-link>
      </ul>
      <router-view class="view"></router-view>
    </div>
  `
}).$mount('#app')

看来你可以简单地使用vue-router提供的router.go(1)方法。此方法根据您传递给该方法的数量在历史堆栈中前进或后退。例如前进 1 你可以做 router.go(1),而后退 1 你可以做 router.go(-1)