Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

WeChat small program condition rendering wx:if


May 18, 2021 WeChat Mini Program Development Document


Table of contents


wx:if

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

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

You can wx:elif block wx:else

<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 a control property, you need to add it to a label. But if we want to judge multiple component labels at once, we can wrap multiple components with a <block/> label and wx:if above.

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

Note: <block/> it is just a wrapper element, does not render anything on the page, and only accepts control properties.

Instance:

wxml: Use view

<!--index.wxml-->
<button bindtap="EventHandle">按钮</button>
<!-- wx:if -->
<view wx:if="{{boolean==true}}">
    <view class="bg_black"></view>
</view>
 <view wx:elif="{{boolean==false}}">
    <view class="bg_red"></view>
</view>

wxss:

/**index.wxss**/
.bg_black {
  height: 200rpx;
  background: lightskyblue;
}

.bg_red {
  height: 200rpx;
  background: lightpink;
}

Js:

// index.js
 
Page({
  data: {
    boolean:false
  },
 
  EventHandle: function(){
    var bol = this.data.boolean;

    this.setData({
      boolean: !bol
     })
  } 
})

Run:

WeChat small program condition rendering wx:if


wx:if vs hidden

Because wx:if may also contain data bindings, when the condition value of wx:if is switched, the frame has a local rendering process because it ensures that the conditional block is destroyed or re-rendered when switching.

wx:if is lazy, if the initial false the frame does nothing and starts rendering locally the first time the condition becomes true.

In contrast, hidden is much simpler, components are always rendered, but simple controls are displayed and hidden.

In general, wx:if a higher switching consumption and hidden has a higher initial rendering consumption. Therefore, it is better to use hidden scenarios if hidden and wx:if is better if wx:if