从 Aurelia 中的子组件的视图模型访问父组件的视图模型属性



我有两个组件:

<parent-component type="permanent">
<div child-component></div>
</parent-component>
class ParentComponentCustomElement {
@bindable public type: string = "permanent";
}
class ChildComponentCustomAttribute {
public attached() {
// how to get the instance of ParentComponentCustomElement here?
}
}

我需要访问父组件的type属性以有条件地向子组件添加一些类。

我可能可以通过 DOM 遍历父树并寻找这个特定的组件,但我认为这不是正确的方法。

您是否尝试过为自定义属性实现 bind(( 方法?尝试这样的事情:

bind(bindingContext, overrideContext) {
console.log(overrideContext.parentOverrideContext.bindingContext.somePropertyFromParentViewModel);
}

来源: http://aurelia.io/hub.html#/doc/article/aurelia/framework/latest/creating-components/3

事实证明,我可以像这样将父视图模型@inject到子组件中:

import {inject, Parent} from 'aurelia-framework';
class ParentComponentCustomElement {
public type: string = "permanent";
}
@inject(Parent.of(ParentComponentCustomElement))
class ChildComponentCustomAttribute {
public constructor(private parent: ParentComponentCustomElement) {}
public attached() {
console.log(this.parent.type); // permanent
}
}

请注意,这也很方便,因为它遍历父树,直到找到您实际要查找的组件,因此可以将子组件包装在完全不同的组件中,这仍然有效。

最新更新