【问题标题】:Vue Router sub-routes not working as expectedVue Router 子路由没有按预期工作
【发布时间】:2016-12-17 14:59:47
【问题描述】:

当尝试使用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 路由相同的组件。什么给了?

【问题讨论】:

    标签: vue.js vue-router


    【解决方案1】:

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

    '/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 的 outlet 内渲染,因为没有匹配的子路由。

    更新:

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

    这就是为什么组件 Station 需要在其模板中包含一个 router-view 元素,并且 ListStationsCreateStation 都会在其中呈现。

    类似这样的:http://jsfiddle.net/naeg67da/329/

    【讨论】:

    • 我试过了,它只在//create 上加载/stations 组件视图。还有其他想法吗?
    • 您是否 100% 确定在 CreateStation 上加载了正确的组件?
    • 是的,因为如果我不使用subRoutes,它会按预期工作。
    • 我知道怎么了...看看这个:jsfiddle.net/naeg67da/329,我会更新我的答案。
    • 感谢您的帮助!所以,基本上,我需要为我的subRoute 组件提取一个父组件以驻留在其中。明白了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-08-30
    • 1970-01-01
    • 1970-01-01
    • 2022-01-22
    • 1970-01-01
    • 2022-01-27
    • 2014-05-02
    相关资源
    最近更新 更多