May 17, 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
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:
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:
1. Can only be a single field binding, such as
<input model:value="值为 {{value}}" />
<input model:value="{{ a + b }}" />
are illegal;
2. Currently, data paths are not yet able, such as
<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
setData 设置自身的属性。例如:
// custom-component.js
Component({
properties: {
myValue: String
},
methods: {
update: function() {
// 更新 myValue
this.setData({
myValue: 'leaf'
})
}
}
})
如果页面这样使用这个组件:
<custom-component model:my-value="{{pageValue}}" />
当组件使用
setData
更新
myValue
时,页面的
this.data.pageValue
也会同时变更,页面 WXML 中所有绑定了
pageValue
的位置也会被一同更新。