天天看點

微信小程式(學習十) -- WXML資料綁定

微信WXML檔案屬于微信視圖層顯示檔案,實際上是一段被微信封裝過的H5代碼,最終也是顯示在微信界面上,它的動态資料來自對應Page的data資料。

例如:(在wxml中顯示我的頭像,對應于page中的data資料(userInfo)),最終顯示效果如下圖。

<!--pages/start/index.wxml-->
  <view class="userinfo">
    <view class="userinfo-avatar-group">
      <image src="{{userInfo.avatarUrl}}"></image>
      <text>大師</text>
    </view>
  </view>
           
// pages/start/index.js
Page({
  /**
   * 頁面的初始資料
   */
  data: {
    userInfo: {}
  },
})
           
微信小程式(學習十) -- WXML資料綁定

如何使用:

需要将要顯示的内容放入到雙引号之内

<image src="{{userInfo.avatarUrl}}"></image>

這裡我們可以使用元件屬性,控制屬性,直接使用關鍵字,邏輯運算,三元運算,算數運算,字元串運算,數組,組合等等

例如:

<button style='background:{{tilesData[index].color}};
width:{{itemSize.width - 2}}rpx;
height:{{itemSize.height-2}}rpx;
line-height: {{itemSize.height-2}}rpx;' 
data-id="{{index}}" 
disabled='{{!tilesData[index].enable}}' 
bindtap='clickMapItem'>
             {{tilesData[index].value == 0 ? "" : tilesData[index].value}} 
          </button>
           

當Page中的data資料有更改的時候,wxml就會更新上面的資料顯示。

使用setData動态更新

this.setData({
      tilesData: this.data.tilesData,
      itemSize: itemSize,
      score: ,
    });
           

我們可以直接使用

this.data.itemSize = itemSize

,這樣設定會講data中的itemSize變量的值更改,但是不會在wxml中顯示出來,是以還需要setData,将需要變更的動态資料傳遞給wxml,wxml才會顯示出來。

繼續閱讀