我希望message
能够在我的应用程序的所有页面中保持不变,并在视图模型和视图有界之后进行设置。每个页面我都有一个非常简单的模板。
<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
!!我想也许当前的指令落后了,所以我添加了另一页。 Page2
如果您愿意,但无论我在第一次导航后做了什么,message
总是Home
因此,应用初始化message
为空白,然后在第一次导航时,message
将保留Home
整体。
我的问题是,获得用户当前所在页面标题的“Aurelia”方式是什么?我认为在每个页面上注入路由器都是昂贵的
答案 0 :(得分:2)
我可以看到两个选项:
第一个也是最简单的一个是使用侦听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
。所以,我选择了第一个选项。
答案 1 :(得分:1)
您可以直接在router.currentInstruction.config.title
页面上使用app.html
,每次更改路由器标题时都会更新它(使用one-way binding):
<h1>title: ${router.currentInstruction.config.title}</h1>
最佳方式(感谢评论):
${router.currentInstruction.config.navModel.title}