# Conditional Rendering
# wx:if
In the framework, use wx:if=""
to determine whether or not to render this code block:
<view wx:if="{{condition}}"> True </view>
You can also use wx:elif
and wx:else
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, you must add it to a tag. To judge multiple component tags at once, you can use a <block/>
tag to package multiple components together and use the wx:if
control property above.
<block wx:if="{{true}}">
<view> view1 </view>
<view> view2 </view>
</block>
Note: <block/>
is not a component, just a package element. It does not perform any rendering on the page and only accepts control properties.
# wx:if
vs hidden
Because the template in wx:if
can also contain data bindings, when the wx:if
condition value changes, the framework has a local rendering process that will ensure the conditional block is destroyed or re-rendered when the value changes.
At the same time, wx:if
is also inert. If the condition is false
during initial rendering, the framework does not render it. When the condition changes to true for the first time, local rendering starts.
In contrast, hidden
is much simpler. The component is always rendered and this property simply controls whether the content is displayed or hidden.
Generally, wx:if
has higher switching costs, while hidden
has higher initial rendering costs. Therefore, in situations with frequent condition changes, it is better to use hidden
. If conditions are unlikely to change during runtime, wx:if
is the better choice.