【问题标题】:Aurelia $parent is undefined on first page loadAurelia $parent 在第一页加载时未定义
【发布时间】:2018-10-20 01:07:40
【问题描述】:

在 Aurelia 中,我目前无法绑定到着陆页中来自父级 (app.ts) 的字段。 如果我明确使用$parent,我会收到一个异常,告诉我$parent 没有定义。

如果我路由到另一个页面并返回登录页面 $parent 现在已定义,我可以直接从父级访问字段而无需使用 $parent 关键字。

我确定它早说,但我认为一些更新的包会破坏它。 (更新后没认出来)

<h1>${testString}</h1><!-- Nothing displayed -->
<h1>${$parent.testString}</h1><!-- ERROR [app-router] TypeError: Cannot read property 'testString' of undefined -->

在页面加载后但在路由回此页面后最初两者都不起作用。

我错过了什么?

使用 aurelia-binding 2.1.5、aurelia-framework 1.3.0、aurelia-router 1.6.3

【问题讨论】:

  • 您是如何创建将app.ts 引用为$parent 的元素的?您是使用&lt;compose&gt; 还是使用自定义元素?
  • 只是路由器打开的一个页面。页面上只有&lt;template&gt;${$parent.testString}&lt;/template&gt;

标签: aurelia


【解决方案1】:

不使用 $parent,而是使用依赖注入来访问父视图模型。

这是GistRun example

test-child.html

<template>
  <h1>${app.message}</h1>
</template>

test-child.js

import {inject} from 'aurelia-framework';
import {App} from './app';

@inject(App)
export class TestChild {
  constructor(app) {
    this.app = app;
  }
}

app.html

<template>
  <require from="./test-child"></require>
  <test-child></test-child>
</template>

app.js

export class App {
  message = 'Hello World';
}

【讨论】:

    猜你喜欢
    • 2019-07-25
    • 2018-03-27
    • 1970-01-01
    • 2014-01-27
    • 1970-01-01
    • 2020-07-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多