如何访问 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.
从'aurelia-router'导入{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');
}
}
这篇关于如何访问 Aurelia 中的子路由器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!