Tìm kiếm trang web

typescript - liên kết hai chiều giữa 2 component con


Mô hình sau hoạt động tốt, tôi có một component cha (app.html + .ts), một component con (test-binding.html + .ts) và một trường input với liên kết hai chiều

thành phần cha

<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');
}
}

Tuy nhiên, tôi không chắc cách thực hiện cùng một chức năng với 2 thành phần tùy chỉnh con. Tôi có thể dễ dàng đạt được điều tương tự bằng cách sử dụng eventAggregator và lắng nghe trong các thành phần con của mình để sự kiện được phát ra, tuy nhiên, tôi đang cố gắng đạt được cùng chức năng bằng cách sử dụng ràng buộc hai chiều. Ví dụ:

thành phần cha (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>

kiểm-tra-nhập.html

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

kiểm tra-nhập.ts

import { bindable } from 'aurelia-framework';

    export class TestInput{
    @bindable query;

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

Câu trả lời #1

Điều cần chú ý ở đây là chế độ ràng buộc mặc định cho bindable (sử dụng bind) thực ra là một chiều. Nếu bạn muốn cả hai component của mình có thể “trao đổi thông tin với nhau”, chỉ cần chỉ định hai chiều trong ràng buộc. Chỉ cần ràng buộc test-input với hai chiều vì nó là cái duy nhất thực sự thay đổi input.

<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>