WeChat Open Platform

Mini Programs Documentation

Conditional rendering


In the framework, we use wx:if="{{condition}}" to determine whether the code block needs to be rendered:

<view wx:if="{{condition}}"> True </view>

wx:elif and wx:else can also be used to add an else block:

<view wx:if="{{length > 5}}"> 1 </view>
<view wx:elif="{{length > 2}}"> 2 </view>
<view wx:else> 3 </view>

block wx:if

Because wx:if is a control property, it needs to have a tag added to it. However, if we want to determine multiple component tags all at once, we can use a <block/> tag to package multiple components and use wx:if above to control attributes.

<block wx:if="{{true}}">
  <view> view1 </view>
  <view> view2 </view>

Note: <block/> is not a component, it is just a wrapper element. It will not do any rendering on a page, it just receives control properties.

wx:if vs hidden

Because the templates in wx:if may also include data binding, the framework has a local rendering process when any wx:if condition values are switched, because it will ensure that the condition block is removed or re-rendered during switching.

wx:if is also lazy. If an initial rendering condition is false, the framework will not do anything. Local rendering will only begin when the condition first becomes true.

In comparison, hidden is a lot simpler. The component will always be rendered, it is just a simple control for display and hiding.

In general, wx:if has higher switching consumption but hidden has higher initial rendering consumption. Therefore, it is better to use hidden in situations where frequent switching is required. If conditions are not too likely to change during running then wx:if is better.