在 Aurelia 中从子组件的 ViewModel 访问父组件的 ViewModel 属性

Accessing a parent component's ViewModel property from the child's ViewModel in 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

原来我可以像这样将父 ViewModel @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
    }
}

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