【问题标题】:How do I get the title of the current Router Config Aurelia如何获取当前路由器配置 Aurelia 的标题
【发布时间】:2017-11-14 23:54:37
【问题描述】:

我希望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 将保持Home 的全部。

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

【问题讨论】:

标签: router aurelia


【解决方案1】:

我可以看到两个选项:

第一个也是最简单的方法是使用监听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。所以,我会选择第一个选项。

【讨论】:

  • 第一个很漂亮,也很优雅。它工作得很好。不幸的是,Visual Studio 到处都抛出了语法错误,我已经养成了在我的 js 文件末尾抛出这些行的习惯。但它们是否是一种对 Visual Studio 更友好的替代语法?
  • 问题是 Visual Studio 还没有准备好 ES6/7 语法。您应该使用带有 Aurelia 插件的 Visual Studio Code,这样效果会更好。如果这个答案解决了你的问题,请标记为正确答案,以帮助以后的其他人
【解决方案2】:

您可以在您的app.html 页面上直接使用router.currentInstruction.config.title,并且每次更改路由器标题时都会更新(它使用one-way binding):

&lt;h1&gt;title: ${router.currentInstruction.config.title}&lt;/h1&gt;

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

【讨论】:

  • 最好使用${router.currentInstruction.config.navModel.title},因为调用routeConfig.navModel.setTitle() 时不会更新config.title。
  • 同上 ^---- ${router.currentInstruction.config.navModel.title}
猜你喜欢
  • 2015-05-28
  • 1970-01-01
  • 2016-10-31
  • 2017-03-23
  • 1970-01-01
  • 1970-01-01
  • 2023-03-12
  • 1970-01-01
  • 2016-12-29
相关资源
最近更新 更多