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

时间:2016-03-20 23:39:24

标签: vue.js vue-router

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

methods : {
 getMenuLinks: function() {

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

 }

我想迭代所有maped路由以获得类似于每个映射路由的下面的内容:

<a v-link="{ path: 'home' }">Home</a>

6 个答案:

答案 0 :(得分:27)

在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: []
        }
    }
}

答案 1 :(得分: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/

答案 2 :(得分:3)

您可以简单地遍历模板中的$router.options.route

<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

答案 3 :(得分:3)

从 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() }
}

答案 4 :(得分:0)

另一种解决方案是使用Webpack的require.context

{{1}}

答案 5 :(得分: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

获取路线