In some scenarios, to change the field at the service layer when a user inputs the value, use the two-way binding capability provided by the engine.
For example, add the prefix model: before the corresponding project. In this way, if the value in the text box is changed, this.data.value is changed accordingly. Also, all components bound to value in the HXML file are updated, and the data listener is triggered.
<input model:value="{{value}}" /> The table below lists the component attributes that support two-way binding.
| Component | Attribute |
|---|---|
| check-box | checked |
| input | value |
| map | latitude |
| map | longitude |
| map | scale |
| map | rotate |
| map | skew |
| radio | checked |
| slider | value |
| text-area | value |
In addition, two-way binding can be used in custom components. The usage is similar to that of built-in components.
The following is an example custom component.
// custom-component.js
Component({
properties: {
myValue: String
}
}); <!-- custom-component.hxml -->
<input model:value="{{myValue}}" /> The myValue property in the custom component is bound to the value property of the text box in a two-way manner. In this way, the execution result is as follows:
<custom-component model:my-value="{{pageValue}}" /> When the value in the text box is changed, myValue of the custom component, this.data.pageValue of the page, and all components bound to pageValue on the page change accordingly.
You can also use setData to trigger the two-way binding of the custom components.
// custom-component.js
Component({
properties: {
myValue: String
},
methods: {
update: function() {
// Update myValue.
this.setData({
myValue: 'leaf'
});
}
}
}); In this way, the execution result is as follows:
<custom-component model:my-value="{{pageValue}}" /> When the component uses setData to update myValue, this.data.pageValue on the page and all components bound to pageValue in the HXML file of the page are also updated.