使用 Aurelia 的 ref 属性引用元素的视图模型

Referencing view-model of element using Aurelia's ref attribute

Aurelia 提供了 ref attribute,除其他外,它应该能够提供对自定义元素的视图模型的引用。

我正在尝试构建一个示例,其中一个文本框(生产者)的值通过管道传输到另一个只读文本框(消费者)。

符合预期:

但是 consumerInput 没有被调用。如果我理解正确的话,它应该在每次调用 producerOutput 后被调用。 consumerInput 未被调用意味着该值未通过管道传输到消费者文本框。为什么 consumerInput 没有被调用,我该如何解决?

ref.html

<template>

    <require from="producer"></require>
    <require from="consumer"></require>

    <producer producer.ref="producerViewModel"></producer>
    <consumer consumerInput.bind="producerViewModel.producerOutput"></consumer>

</template>

ref.js

export class Ref {

}

producer.html

<template>
    <div>
        producer: <input value.bind="producerInput" />
    </div>
</template>

producer.js

import {customElement} from 'aurelia-framework';

@customElement('producer')
export class Producer {

    set producerInput(v) {
        this.value = v;
    }

    get producerOutput() {
        return this.value;
    }

}

consumer.html

<template>
    <div>
        consumer: <input value.bind="consumerOutput" readonly />
    </div>
</template>

consumer.js

import {customElement, bindable} from 'aurelia-framework';

@customElement('consumer')
@bindable('consumerInput')
export class Consumer { 

    set consumerInput(v) {
        this.value = v;
    }

    get consumerOutput() {
        return this.value;
    }

}

更新的工作解决方案:

ref.html:

<template>

    <require from="producer"></require>
    <require from="consumer"></require>

    <producer producer.ref="producerViewModel"></producer>
    <consumer input.bind="producerViewModel.output"></consumer>

</template>

ref.js

export class Ref {

}

producer.html

<template>
    <div>
        producer: <input value.bind="output" />
    </div>
</template>

producer.js

import {bindable} from 'aurelia-framework';

export class Producer {

    @bindable output;

}

consumer.html

<template>
    <div>
        consumer: <input value.bind="input" readonly />
    </div>
</template>

consumer.js

import {bindable} from 'aurelia-framework';

export class Consumer { 

    @bindable input;

}

DOM 自动小写所有属性。您不能使用 consumerInputproducerOutput 作为可绑定的 属性 名称。 Aurelia 使用一种约定,将具有混合大小写的可绑定 属性 名称连字符连接起来。

例如,class MyElement { @bindable fooBar } 可以这样使用:

<my-element foo-bar.bind="baz"></my-element>

试试这个:

import {customElement, bindable} from 'aurelia-framework';

@customElement('consumer')
export class Consumer { 
    @bindable input;

    inputChanged(newValue, oldValue) {
      // aurelia will call this automatically- a convention looks for methods on the vm that match bindable property names.
    }
}

生产者自定义元素需要进行类似的更改。