# Simple two-way binding

Start from base library version 2.9.3. Please remaining backward compatible.

# Bidirectional binding syntax

in WXML The binding of ordinary properties is unidirectional. For example:

<input value="{{value}}" />

If you use this.setData({ value: 'leaf' }) To update valuethis.data.value And the values shown in the input fields are updated to leaf But if the user modifies the value in the input field, it doesn't change it at the same time. this.data.value

If you need to change at the same time as user input this.data.value , requires a simple two-way binding mechanism. At this point, you can add before the corresponding item model: Prefix:

<input model:value="{{value}}" />

This way, if the value of the input box is changed, this.data.value Will change at the same time. At the same time, WXML All bound in. value Will be updated along with it, Data listener Will be triggered normally.

{% Minicode ('8jXvobmV7vcj') %}

Expressions used for bidirectional binding have the following limitations:

  1. Can only be a binding of a single field, such as
<input model:value="A value of {{value}}" />
<input model:value="{{ a + b }}" />

Are illegal.

  1. At present, it is not possible Data Path, such as
<input model:value="{{ a.b }}" />

Such expressions are not currently supported.

# Passing Bidirectional Binding in Custom Components

Two-way binding can also be used with custom components. The following custom components:

// custom-component.js
Component({
  properties: {
    myValue: String
  }
})
<!-- custom-component.wxml -->
<input model:value="{{myValue}}" />

This custom component converts its own myValue Property is bidirectionally bound to the input field of the component value Property on. So, if the page uses this component like this:

<custom-component model:my-value="{{pageValue}}" />

When the value of the input box changes, the custom component's myValue Properties change at the same time. This way, the page's this.data.pageValue The page will change at the same time. WXML All bound in. pageValue The location will also be updated.

# Triggering bidirectional binding updates in custom components

Custom components can also trigger bidirectional binding updates themselves by using setData Sets its own properties. For example:

// custom-component.js
Component({
  properties: {
    myValue: String
  },
  methods: {
    update: function() {
      // To update myValue
      this.setData({
        myValue: 'leaf'
      })
    }
  }
})

If the page uses this component like this:

<custom-component model:my-value="{{pageValue}}" />

When a component uses setData To update myValue When the page's this.data.pageValue The page will change at the same time. WXML All bound in. pageValue The location will also be updated.