Vue Router子路由未按预期工作

时间:2016-08-11 03:23:25

标签: vue.js vue-router

当尝试使用vue-router使子路由工作时,我的子路由正在呈现父路由组件,而不是该子路由的已声明组件。似乎必须为父路由声明组件 ,否则根本不会显示任何组件。例如,如果我声明我的路线:

Router.map({
    '/login': {
        component: Login
    },
    '/stations': {
        subRoutes: {
            '/': {
                component: Station
            },
            '/create': {
                component: CreateStation
            }
        }
    },
});

任何路线都不显示任何内容。但如果我宣布我的路线是这样的:

Router.map({
    '/login': {
        component: Login
    },
    '/stations': {
        component: Station,
        subRoutes: {
            '/create': {
                component: CreateStation
            }
        }
    },
});

我的stations/create路由显示与stations路由相同的组件。是什么给了什么?

1 个答案:

答案 0 :(得分:2)

您仍然需要为root路由声明/stations组件,如下所示:

'/stations': {
    component: Station,
    subRoutes: {
        '/': {
            component: ListStations
        },
        '/create': {
            component: CreateStation
        }
    }
}

根据文件:

router.map({
  '/foo': {
    component: Foo,
    // add a subRoutes map under /foo
    subRoutes: {
      '/bar': {
        // Bar will be rendered inside Foo's <router-view>
        // when /foo/bar is matched
        component: Bar
      },
      '/baz': {
        // Same for Baz, but only when /foo/baz is matched
        component: Baz
      }
    }
  }
})
  

现在,通过上面的配置,当你访问/ foo时,什么都不会   在Foo的出口内呈现,因为没有子路线匹配。

<强>更新

当您创建子路由时,您告诉父组件(在本例中为Station),它需要在其模板中托管一些组件。 Station和CreateStation不是并排放置的,它们具有父子关系(就路线而言)。

这就是组件工作站需要在其模板中添加router-view元素的原因,ListStationsCreateStation都会在其中呈现。

像这样:http://jsfiddle.net/naeg67da/329/

相关问题