Understanding WXML: The View Layer in WeChat Mini Programs
WXML (WeChat Markup Language) is a tag-based language used to define the structure of pages in WeChat Mini Programs, integrating with components and events.
Data Binding
Dynamic data in WXML is sourced from the data object of the corresponding Page.
Basic Binding
Use Mustache syntax ({{}}) to bind variables, applicable to:
- Content:
<view>{{textContent}}</view> - Component Attributes:
<view id="item-{{itemId}}"></view> - Control Attributes:
<view wx:if="{{isVisible}}"></view> - Keywords:
<checkbox checked="{{false}}"></checkbox>(Note: Avoidchecked="false"as it's a string that evaluates to true.)
Operations in Binding
Perform simple operations within {{}}:
- Ternary Operation:
<view hidden="{{shouldHide ? true : false}}">Hidden</view> - Arithmetic:
<view>{{x + y}} + {{z}} + w</view> - Logical Comparison:
<view wx:if="{{count > 5}}"></view> - String Concatenation:
<view>{{'Hello ' + userName}}</view> - Path Access:
<view>{{obj.property}} {{arr[0]}}</view>
Data Combinasion
Combine data within Mustache to form new arrays or objects:
- Array:
<view wx:for="{{[startVal, 1, 2, 3]}}">{{element}}</view> - Object:
<template is="combineTemplate" data="{{key1: val1, key2: val2}}"></template> - Use spread operator:
<template is="combineTemplate" data="{{...objA, ...objB, extra: 5}}"></template> - Shorthand for same key-value:
<template is="combineTemplate" data="{{prop1, prop2}}"></template>
Note: Overlapping keys resolve with later values taking precedence. Spaces between braces and quotes are parsed as strings.
List Rendering
wx:for
Bind an array to wx:for to render components repeatedly. Default variables: index for current index, item for current element.
<view wx:for="{{items}}">
{{position}}: {{element.label}}
</view>
Customize with wx:for-index and wx:for-item:
<view wx:for="{{items}}" wx:for-index="pos" wx:for-item="elem">
{{pos}}: {{elem.label}}
</view>
Nested example for multiplication table:
<view wx:for="{{[1,2,3,4,5]}}" wx:for-item="i">
<view wx:for="{{[1,2,3,4,5]}}" wx:for-item="j">
<view wx:if="{{i <= j}}">
{{i}} * {{j}} = {{i * j}}
</view>
</view>
</view>
block wx:for
Use <block> with wx:for to render multiple nodes:
<block wx:for="{{[1, 2, 3]}}">
<view>{{index}}:</view>
<view>{{item}}</view>
</block>
wx:key
Specify wx:key for dynamic lists to maintain component state. Values can be a unique property string or *this for the item itself. Omitting it may cause warnings for static lists.
Note: String values in wx:for are parsed as character arrays, and spaces between braces and quotes become strings.
Conditional Rendering
wx:if
Use wx:if, wx:elif, and wx:else to conditionally render blocks.
<view wx:if="{{score > 90}}">A</view>
<view wx:elif="{{score > 60}}">B</view>
<view wx:else>C</view>
block wx:if
Wrap multiple components in <block> for grouped conditions.
<block wx:if="{{isActive}}">
<view>Component1</view>
<view>Component2</view>
</block>
<block> is a non-rendering wrapper.
wx:if vs hidden
wx:if conditionally renders or destroys components, suitable for infrequent changes. hidden toggles visibility without re-rendering, better for frequent switches.
Templates
Define reusable code snippets with <template>.
Defining Templates
Use name attribute to identify templates.
<template name="infoTemplate">
<view>
<text>{{id}}: {{message}}</text>
<text>Date: {{date}}</text>
</view>
</template>
Using Templates
Reference with is attribute and pass data via data.
<template is="infoTemplate" data="{{...infoData}}"/>
Dynamic template selection:
<template name="oddTemplate">
<view>Odd</view>
</template>
<template name="evenTemplate">
<view>Even</view>
</template>
<block wx:for="{{[1, 2, 3, 4]}}">
<template is="{{num % 2 == 0 ? 'evenTemplate' : 'oddTemplate'}}"/>
</block>
Templates have isolated scope, using only passed data and defined WXS modules.
References
import
Import templates from other files with import.
<import src="templateFile.wxml"/>
<template is="importedTemplate" data="{{label: 'Example'}}"/>
Import scope is limited to directly imported templates.
include
Include entire file content except <template> and <wxs>.
<include src="header.wxml"/>
<view>Main Content</view>
<include src="footer.wxml"/>
Events
Events facilitate communication from the view to logic layer.
Event Usage
Bind event handlers to components, e.g., bindtap for tap events.
<view id="clickable" data-info="Sample" bindtap="handleClick">Click Here</view>
Define handler in Page:
Page({
handleClick: function(event) {
console.log(event);
}
});
Event object includes properties like type, timeStamp, target, dataset, touches, changedTouches, and detail.
Event Categories
- Bubbling Events: Propagate to parent nodes (e.g.,
tap). - Non-bubbling Events: Do not propagate (e.g.,
submit).
Event Binding and Bubbling
bindprefixes allow bubbling;catchprefixes prevent it.- Example with bubbling: inner view triggers handlers in sequence unless stopped.
Capture Phase
For touch events, use capture-bind to listen in capture phase (reverse order of bubbling). capture-catch interrupts capture and bublbing.
Event Object Details
type: Event type.timeStamp: Millliseconds since page open.target: Source component.currentTarget: Component where event is bound.dataset: Data attributes (hyphenated names convert to camelCase).touches/changedTouches: Touch point arrays.detail: Custom data (e.g., coordinates for click events).