# Easy two-way bonding
Start from base library version 2.9.3. Please remaining backward compatible.
# Two-way binding syntax
In WXML, normal property bindings are unidirectional. For example:
<input value="{{value}}" />
If you usethis.setData ({value: 'leaf'})to updatevalue,this.data.valueand the value displayed in the input box will be updated toleaf;But if the user changes the value in the input box, it does not changethis.data.value.
If you need to changethis.data.valueat the same time as user input, you need to use a simple two-way binding mechanism.In this case, the corresponding item can be preceded by themodel:prefix:
<input model:value="{{value}}" />
Thus, if the value of the input box is changed,this.data.valuewill also change.At the same time, all locations in WXML that bind thevalueare updated together, and the data listener is normally triggered.
Expressions used for two-way binding have the following limitations:
- It can only be bound by a single field, such as
<input model:value="值为 {{value}}" />
<input model:value="{{ a + b }}" />
They are all illegal;
- Currently, there is no data path, such as
<input model:value="{{ a.b }}" />
Such an expression is not supported at this time.
# Pass a two-way binding in a custom component
Two-way binding can also be used on custom components. The following custom components are:
// custom-component.js
Component({
properties: {
myValue: String
}
})
<!-- custom-component.wxml -->
<input model:value="{{myValue}}" />
This custom component binds its ownmyValueattribute to thevalueattributes of the input box within the component.So, if the page uses this component like this:
<custom-component model:my-value="{{pageValue}}" />
When the value of the input box changes, themyValueproperty of the custom component changes at the same time,This way, thethis.data.pageValueof the page will also change at the same time, and all positions in the WXML of the page that bind thepageValuewill be updated together.
# Trigger two-way binding updates in custom components
Custom components can also trigger bidirectional binding updates themselves by using setData to set their own properties. For example:
// custom-component.js
Component({
properties: {
myValue: String
},
methods: {
update: function() {
// 更新 myValue
this.setData({
myValue: 'leaf'
})
}
}
})
If the page uses this component as follows:
<custom-component model:my-value="{{pageValue}}" />
When the component is updated withsetDatamyValueAt this time, thethis.data.pageValueof the page will also change at the same time, and all positions in the WXML of the page that bind thepageValue`will be updated together.