【问题标题】:two-way binding 2 child components双向绑定2个子组件
【发布时间】:2018-08-05 03:10:58
【问题描述】:

以下模型工作正常,我有一个 prent 组件 (app.html + .ts) 一个子组件 (test-binding.html + .ts) 和一个双向绑定的输入字段

父组件

<template bindable="query">
    <require from="./test-bindable"></require>

    <input type="text" value.bind="query"/>
    <test-bindable query.bind="query"></test-bindable>

</template>

test-bindable.html

<template>
    <div>${query}</div>
</template>

test-bindable.ts

import { bindable } from 'aurelia-framework';

export class TestBindable{
@bindable query = 'potato';

valueChange(newValue, oldValue)
{
    //Do something
}
created(){
    console.log('test component created');
}
}

但是,我不确定如何使用 2 个子自定义组件实现相同的功能。我可以使用eventAggregator 轻松实现相同的目的,并在我的子组件中侦听要触发的事件,但是,我正在尝试使用两种方式绑定来实现相同的功能。例如:

父组件(app.html)

<template bindable="query">
    <require from="./test-bindable"></require>
    <require from="./test-input"></require>

    <test-input value.bind="query"></test-bindable>
    <test-bindable query.bind="query"></test-bindable>
</template>

测试输入.html

<template>
    input type="text" value.bind="test"/>
</template>

测试输入.ts

import { bindable } from 'aurelia-framework';

    export class TestInput{
    @bindable query;

    valueChange(newValue, oldValue)
    {
        //Do something
    }
    created(){
        console.log('test component created');
    }
}

【问题讨论】:

    标签: typescript aurelia two-way-binding


    【解决方案1】:

    这里要注意的是,bindable(使用bind)的默认绑定模式实际上是one-way。 如果您希望您的两个组件“互相交谈”,只需在绑定中指定two-way。 将test-inputtwo-way 绑定就足够了,因为他是唯一真正更改输入的人。

    <template bindable="query">
        <require from="./test-bindable"></require>
        <require from="./test-input"></require>
    
        <test-input value.two-way="query"></test-bindable>
        <test-bindable query.bind="query"></test-bindable>
    </template>
    

    【讨论】:

    • 默认绑定模式是one-wayto-view 用于非表单html元素,当然这包括自定义组件。对于输入和选择等表单字段,默认绑定模式为two-way
    • 这就是我为bindable指定默认绑定模式的原因
    • 我知道。我并不是要纠正你,我只是想补充一下.bind默认情况下的双向时间。这种行为似乎并不是每个人都清楚。
    猜你喜欢
    • 2017-02-11
    • 2016-11-19
    • 1970-01-01
    • 2017-11-03
    • 2017-04-29
    • 2017-06-19
    • 1970-01-01
    • 2019-08-18
    • 2018-02-13
    相关资源
    最近更新 更多