繁体   English   中英

如何获得当前路由器配置Aurelia的标题

[英]How do I get the title of the current Router Config Aurelia

我希望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 !! 我认为也许currentInstruction落后了,所以我添加了另一页。 如果愿意的话,第Page2 ,但是无论我第一次导航后做什么,该message始终为Home

因此,在应用程序上,初始化message为空白,然后在第一次导航message中,整个message将保留为Home

我的问题是,获取用户当前所在的每个页面的标题的“ Aurelia”方法是什么? 我认为在每个页面上注入路由器的成本很高

我可以看到两个选项:

第一个也是最简单的方法是使用getter属性,该属性侦听router.currentInstruction 例如:

@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 所以,我会选择第一个选项。

您可以直接在app.html页面上使用router.currentInstruction.config.title ,并且每次更改路由器标题(使用单向绑定 )时都会对其进行更新:

<h1>title: ${router.currentInstruction.config.title}</h1>

最佳方式(感谢评论): ${router.currentInstruction.config.navModel.title}

暂无
暂无

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

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