获取vue路由器中的所有路由

问题描述 投票:0回答:6

我正在尝试使用 vue 路由器创建一个简单的菜单,我想迭代所有路由并将它们显示在我的菜单中,目前我在组件中使用下面的实例方法,但我只是得到一个函数,我将如何迭代获取单独的路线?

methods : {
 getMenuLinks: function() {
        
        var t = this.$router.map() ;
        //t returns a vue object instance
        return t._children ;
        // did not know how to iterate this 
   }

 }

我想迭代所有映射的路线以获得每条映射路线的如下内容:

<a v-link="{ path: 'home' }">Home</a>
vue.js vuejs2 vue-router
6个回答
69
投票

在 Nuxt 中,路由是自动生成的,所以我无法执行 @zxzak 建议的操作。

在这种情况下您可以采取以下措施。

<template v-for="item in items">
    <b-nav-item :to="item.path">
        {{item.name}}
    </b-nav-item>
</template>
export default {
    created() {
        this.$router.options.routes.forEach(route => {
            this.items.push({
                name: route.name
                , path: route.path
            })
        })
    }
    , data() {
        return {
            items: []
        }
    }
}

27
投票

您可以简单地在模板中迭代

$router.options.routes

<nav>
  <router-link v-for="route in $router.options.routes" :key="route.path" :to="route.path">{{ route.name }}</router-link>
</nav>

也许为所选路线添加样式:

:class="{ active: route.path === $router.currentRoute.path }"

编辑:对于活动类,请使用 https://router.vuejs.org/api/#active-class 代替


10
投票

从 vue-router 3.5 开始,Router 实例现在有一个 getRoutes() 方法。
所以最新的答案可能是

<router-link 
    for="r in routes" 
    :key="r.path" 
    :to="r.path"
>
    {{ r.name }}
</router-link>
computed: {
    routes() { return this.$router.getRoutes() }
}

5
投票

不要依赖 Vue 的内部结构,而是将路由放入起始组件的数据中。

var map = {
  '/foo': {
    component: Foo
  },
  '/bar': {
    component: Bar
  }
}

var routes = Object.keys(map)

var App = Vue.extend({
  data: function() {
    return {
      routes: routes
    }
  }
})

router.map(map)
router.start(App, '#app')

http://jsfiddle.net/xyu276sa/380/


1
投票

另一个解决方案是使用 Webpack 的

require.context

// search for src/pages/**/index.vue
function routesGen () {
  const pages = require.context('./pages/', true, /index\.vue$/)
  const filePaths = pages.keys()
  const getRoutePath = filePath => filePath.match(/\.(\/\S+)\/index\.vue/)[1]
  return filePaths.map(filePath => ({
    path: getRoutePath(filePath),
    component: pages(filePath).default
  }))
}

0
投票

由于

VueRouter
与其他类一样只是一个 JavaScript 类,因此您可以扩展它并添加任何自定义功能,包括有问题的功能:

// TypeScript

import Vue from 'vue';
import VueRouter, { RouteConfig } from 'vue-router';

class VueRouterEx extends VueRouter {
  matcher: any;

  public routes: RouteConfig[] = [];

  constructor(options) {
    super(options);
    const { addRoutes } = this.matcher;
    const { routes } = options;

    this.routes = routes;

    this.matcher.addRoutes = (newRoutes) => {
      this.routes.push(...newRoutes);
      addRoutes(newRoutes);
    };
  }
}

Vue.use(VueRouterEx);

const router = new VueRouterEx({
  mode: 'history',
  base: process.env.BASE_URL,
  routes: [],
});

export default router;

因此,从任何组件,您都可以使用

this.$router.routes

获取路线
© www.soinside.com 2019 - 2024. All rights reserved.