如何在 Vue 路由器中动态设置目标组件

How can I dynamically set destination component in Vue router

我正在尝试为 vue-router 路由动态设置目标组件。

原因是我需要从服务器检索数据以了解要定位的正确组件。

我想到的一个解决方案是添加一个全局守卫,类似于:

router.beforeEach((to, from, next) => {
  get_data_from_server(to.fullPath).then(() => {
    // set the "to" component, but how?
    next();
})

但是,正如评论所说,我将如何设置 "component" - "to" 对象中没有组件 属性。 (看起来它在 components.default.render 中,但没有记录在案,而且看起来不应该被弄乱。)

另一种替代方法是使用上述逻辑,但添加特殊情况代码进行重定向,但后来我发现无法创建针对正确组件的 dynamic/new 路由。

应该如何创建一条通往在构建时未知的目的地的路线?

这个解决方案似乎有效。

router.beforeEach((to, from, next) => {
  get_data_from_server(to.fullPath).then(component => {
    if (to.matched.length === 0) {
      // the target route doesn't exist yet
      router.addRoutes({path: to.path, component: component})
      next(to.fullPath)
      return
    } else {
      // the route and component are known and data is available
      next()
    }
})

关键是在我上面的评论中找到 link,它显示了实现 addRoutes().

的 vue-router 提交

需要注意的一件事是在末尾添加了新路由(有道理),因此存在的任何通配符都可能会产生意外的匹配。我有一个重定向到默认页面的包罗万象的路由。但这在新添加的匹配之前匹配,因为它在列表的前面。这导致了堆栈溢出。实际上 if (to.matched.length === 0) 之后的代码是默认路由。