WeChat applet conditional rendering wx:if
wx:if
In MINA, we use wx:if="{{condition}}"
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 that needs to be added to a label. But if we want to judge multiple component tags at once, we can use a <block/>
tag to wrap multiple components, and use wx:if
control on it Attributes.
<block wx:if="{{true}}"> <view> view1 </view> <view> view2 </view> </block>
Note: <block/>
is not a component, it is just a wrapping element, it will not do any rendering in the page, only accept Control properties.
wx:if
vs hidden
Because the template in wx:if
may also contain data binding, So when the condition value of wx:if
is switched, MINA has a partial 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
, MINA will do nothing. In the first condition Local rendering starts only when it becomes true for the first time.
In contrast, hidden
is much simpler. The component will always be rendered, and it is just a simple control of display and hiding.
Generally speaking, wx:if
has a higher switching cost and hidden
has a higher initial rendering cost. Therefore, if frequent switching is required, it is better to use hidden
. If the conditions are unlikely to change during runtime, wx:if
is better.