简体   繁体   English

如何访问Aurelia的儿童路由器?

[英]How to access child router in Aurelia?

I have two child routers. 我有两个子路由器。 I can navigate from one to other. 我可以从一个导航到另一个。 But from the child router view, how can I navigate? 但是从子路由器视图中,我该如何导航?

Below line of code gives the parent router instance. 下面的代码行给出了父路由器实例。

import {Router} from 'aurelia-router'

How to get child router instance? 如何获取子路由器实例?

To create a child router, create a new router on a child route in the same way you created a router on the parent route. 要创建子路由器,请在子路由上创建新路由器,方法与在父路由上创建路由器的方式相同。 Then, set the router as a property of the view model class so you can access it throughout your view model. 然后,将路由器设置为视图模型类的属性,以便您可以在整个视图模型中访问它。

import { Router } from 'aurelia-router';

class ChildViewModel() {  
    configureRouter(config, router) {
        this.router = router;
        // router config
    }
    someOtherFunction() {
        this.router.navigate('somewhere');
    }
}

If you then want to use the child router in another view model, you can import it and use the router on the class (assuming that the class is a singleton, which it should be unless you configure it otherwise). 如果您希望在另一个视图模型中使用子路由器,则可以导入它并在类上使用路由器(假设该类是单例,除非您另外配置,否则应该是该单元)。

import { inject } from 'aurelia-framework';
import { ChildViewModel } from './child-view-model';

@inject(ChildViewModel)
class AnotherViewModel() {
    constructor(cvm) {
        this.externalRouter = cvm.router;
    }
    doStuff() {
        this.externalRouter.navigate('somewhere');
    }
    doOtherStuff() {
        ChildViewModel.router.navigate('somewhere else');
    }
}

My friend helped me solve this. 我的朋友帮我解决了这个问题。 For the child router on first router navigation I had blank '' and it took the URL with like localhost:9000/. 对于第一个路由器导航中的子路由器,我有空白''并且它使用了类似localhost:9000 /的URL。 When I try to navigate from there I had problem. 当我尝试从那里导航时,我遇到了问题。 So from the first navigation, I changed to the code to route like childrouter/name and it worked. 所以从第一个导航,我改为代码路由像childrouter / name一样工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM