Conditional Rendering
wx:if
In the framework, use wx:if='' to determine whether the code block needs to be rendered:
<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 attribute, it needs to be added to a tag. If you want to judge multiple component tags at one time, you can use a <block/> tag to wrap multiple components and use the wx:if control attribute on it.
<block wx:if="{{true}}">
<view> view1 </view>
<view> view2 </view>
</block>TIP
<block/>It is not a component, it is just a wrapper element, it will not do any rendering in the page, and only accepts control attributes.
wx:if vs hidden
Because the template in wx:if may also contain data binding, when the conditional value of wx:if is switched, the framework has a local rendering process, because it will ensure that the conditional block is destroyed or re-rendered when switching.
At the same time, wx:if is also lazy. If the initial rendering condition is false, the framework does nothing and starts local rendering when the condition becomes true for the first time.
In contrast, hidden is much simpler. The component will always be rendered, but it simply controls display and hiding.
Generally speaking, wx:if has higher switching cost and hidden has higher initial rendering cost. Therefore, if frequent switching is required, it is better to use hidden. If the conditions are unlikely to change at runtime, wx:if is better.