我希望消息
在我的应用程序的所有页面中持久存在,并在 View 模型和 View 绑定(bind)后进行设置。我的每个页面都有一个非常简单的模板。
<template>
<h1>${message}</h1>
</template>
每个页面(“Page1”、“Home”、“Page2”)后面的代码都是空的。 这是我的 app.js
import {inject} from 'aurelia-framework';
export class App {
configureRouter(config, router) {
config.title = 'Pathways';
config.map([
{ route: ['','home'], name: 'home', moduleId: 'home', nav: true, title:'Home' },
{ route: 'page1', name: 'page1', moduleId: 'page1', nav: true, title:'Page1' }
]);
// Create a binding to the router object
this.router = router;
}
attached() {
this.message = this.router.currentInstruction.config.title;
}
}
问题是,当我第一次加载应用程序时。 ${message}
为空。然后,当我导航到 page1 时,消息变为 Home
!!我想可能是currentInstruction落后了,所以我又添加了一个页面。 Page2
如果你愿意的话,但事实证明,无论我在第一次导航后做什么,message
始终是 Home
因此,在应用初始化时消息
为空白,然后在第一次导航时消息
将始终保持Home
。
我的问题是,获取用户当前所在的每个页面的标题的“Aurelia”方式是什么?我认为在每个页面上注入(inject)路由器的成本很高
最佳答案
我可以看到两个选项:
第一个也是最简单的一个是使用一个监听 router.currentInstruction
的 getter 属性。例如:
@computedFrom('router.currentInstruction')
get message() {
if (this.router.currentInstruction !== null)
return this.router.currentInstruction.config.title;
}
运行示例 https://gist.run/?id=b01abe2859bc2bea1af0f8d21fc2045f
第二个选项是使用EventAggregator。例如:
attached() {
this.subscription = this.ea.subscribe('router:navigation:success', () => {
this.message = this.router.currentInstruction.config.title;
});
}
detached() {
this.subscription.dispose(); //remember to always dispose the subscription
}
运行示例https://gist.run/?id=7d30d4e8d479cc209ca9013e10e91505
他们说我们应该尽量避免 EventAggregator
。所以,我会选择第一个选项。
关于router - 如何获取当前路由器配置 Aurelia 的标题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40046434/