【问题标题】:load routes from api and import views dynamically从 api 加载路由并动态导入视图
【发布时间】:2019-10-13 02:40:33
【问题描述】:

我的大部分路线都受到保护,需要获得访问权限。当用户成功登录时,我的Navbar 组件会进行 API 调用并检索用户能够访问的一组路由。

之后,我将所有与路由匹配的视图文件添加到导航栏。

这是一个显示过程的示例代码

<template>
  <div>
    <router-link
      v-for="navItem in navItems"
      :key="navItem.title"
      :to="navItem.url"
    >{{ navItem.title }}</router-link>
  </div>
</template>

<script>
export default {
  data: function() {
    return {
      navItems: []
    };
  },
  created: async function() { // Setup the router here
    this.navItems = [
      // !!! API CALL !!!
      {
        title: "Dashboard",
        url: "/Dashboard"
      },
      {
        title: "Users",
        url: "/users/Users"
      },
      {
        title: "Groups",
        url: "/groups/Groups"
      }
    ];

    const routes = await this.navItems.map(async navItem => {
      const { url } = navItem;

      return {
        path: url,
        component: await import(`../views${url}.vue`)
      };
    });

    this.$router.addRoutes(routes);
  }
};
</script>

很遗憾我收到了这个错误

Uncaught (in promise) 错误:[vue-router] "path" is required in a 路由配置。

但正如您在示例代码中看到的那样,此属性已设置。我在这里创建了一个示例项目

https://codesandbox.io/s/vue-routing-example-i2znt

如果你调用这条路线

https://i2znt.codesandbox.io/#/Dashboard

我希望路由器呈现Dashboard.vue 文件。

【问题讨论】:

    标签: vue.js vue-router


    【解决方案1】:

    您构建的 routes 数组不包含您的 routes 对象。 这是一系列的承诺。

    你应该做类似的事情

    Promise.all(routes).then(resolvedRoutes => {
        this.$router.addRoutes(resolvedRoutes)
    })
    

    【讨论】:

      猜你喜欢
      • 2014-08-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-30
      • 2020-09-22
      • 2021-01-25
      • 2019-06-21
      • 1970-01-01
      相关资源
      最近更新 更多