May 18, 2021 WeChat Mini Program Development Document
Base Library 2.9.3 starts to support, and low versions need to be compatible.
In WXML, the binding of normal properties is one-way. For example:
<input value="{{value}}" />
If you update
value
with
this.setData({ value: 'leaf' })
the values displayed in
this.data.value
and the input box are updated to leaf, but if the user modifies the values in the input
this.data.value
If you need to change
this.data.value
you need to use a simple two-way binding mechanism.
At this point, you can add the
model
before the corresponding project:
<input model:value="{{value}}" />
This way, if the value of the input box is changed,
this.data.value
at the same time.
At the same time, all value-bound locations
value
are updated together,
and data listeners are
triggered normally.
Expressions for bidirectional binding have the following limitations:
<input model:value="值为 {{value}}" />
<input model:value="{{ a + b }}" />
are illegal;
Currently, data paths, such as , are not yet able
<input model:value="{{ a.b }}" />
Such expressions are not currently supported.
Bidirectional binding can also be used on custom components. The following custom components:
// custom-component.js
Component({
properties: {
myValue: String
}
})
<!-- custom-component.wxml -->
<input model:value="{{myValue}}" />
This custom component binds its
myValue
in both directions to the value property of the
value
within the component.
This way, if the page uses this component this way:
<custom-component model:my-value="{{pageValue}}" />
When the value of the input box changes,
myValue
component changes at the same time, so that the
this.data.pageValue
at the same time, and all the locations in the page WXML that
pageValue
are updated together.
Custom components can also trigger two-way binding updates themselves by setting their own properties using setData. For example:
// custom-component.js
Component({
properties: {
myValue: String
},
methods: {
update: function() {
// 更新 myValue
this.setData({
myValue: 'leaf'
})
}
}
})
If the page uses this component this way:
<custom-component model:my-value="{{pageValue}}" />
When a component updates
myValue
setData
this.data.pageValue
at the same time, and all
pageValue
bound to the page WXML are updated together.