WeChat Mini Program Data Binding


Data binding

The dynamic data in WXML comes from the data of the corresponding Page.

Simple binding

Data binding uses "Mustache" syntax (double braces) to wrap variables, which can be applied to:

Content

<view> {{ message }} </view>
Page({
  data: {
    message: 'Hello MINA!'
  }
})

Component properties (need to be within double quotes)

<view id="item-{{id}}"> </view>
Page({
  data: {
    id: 0
  }
})

Control properties (need to be within double quotes)

<view wx:if="{{condition}}"> </view>
Page({
  data: {
    condition: true
  }
})

Keywords (need to be within double quotes)

true: true of boolean type, representing true value.

false: boolean type false, representing a false value.

<checkbox checked="{{false}}"> </checkbox>

Special note: Do not write directly checked="false". The calculation result is a string, which after being converted to boolean type represents a true value.


Operation

You can perform simple operations within {{}}. The following methods are supported:

Ternary operation

<view hidden="{{flag ? true : false}}"> Hidden </view>

Arithmetic operation

<view> {{a + b}} + {{c}} + d </view>
Page({
  data: {
    a: 1,
    b: 2,
    c: 3
  }
})

The content in view is 3 + 3 + d

Logical judgment

<view wx:if="{{length > 5}}"> </view>

String operation

<view>{{"hello" + name}}</view>
Page({
  data:{
    name:"MINA"
  }
})

Data path operation

<view>{{object.key}} {{array[0]}}</view>
Page({  data: {
    object: {
      key: 'Hello '
    },    array: ['MINA']
  }
})

Composition

You can also combine it directly in Mustache to form a new object or Array

Array

<view wx:for-items="{{[zero, 1, 2, 3, 4]}}"> {{item}} </view>
Page({
  data: {
    zero: 0
  }
})

Finally combined into array [0, 1, 2, 3, 4]

Object

<template is="objectCombine" data="{{for: a, bar: b}}"></template>
Page({
  data: {
    a: 1,
    b: 2
  }
})

The final combined object is {for: 1, bar: 2}

You can also use the spread operator... to expand an object

<template is="objectCombine" data="{{...obj1, ...obj2, e: 5}}"></template>
Page({
  data: {
    obj1: {
      a: 1,
      b: 2
    },
    obj2: {
      c: 3,
      d: 4
    }
  }
})

Final combination The resulting object is {a: 1, b: 2, c: 3, d: 4, e: 5}

If the key and value of the object are the same, they can also be expressed indirectly

<template is="objectCombine" data="{{foo, bar}}"></template>
rrree

The final combined object is{foo: 'my-foo', bar:'my-bar'}

##Note: The above methods can be combined at will, but if there are the same variable names, the later ones will overwrite the previous ones. For example,

Page({
  data: {
    foo: 'my-foo',
    bar: 'my-bar'
  }
})
<template is="objectCombine" data="{{...obj1, ...obj2, a, c: 6}}"></template>

The final combined object is

{a: 5, b: 3, c: 6}