微信小程序 純數(shù)據(jù)字段

2020-07-31 13:35 更新

純數(shù)據(jù)字段

純數(shù)據(jù)字段是一些不用于界面渲染的 data 字段,可以用于提升頁面更新性能。從小程序基礎(chǔ)庫版本 2.8.2 開始支持。

組件數(shù)據(jù)中的純數(shù)據(jù)字段

有些情況下,某些 data 中的字段(包括 setData 設(shè)置的字段)既不會展示在界面上,也不會傳遞給其他組件,僅僅在當前組件內(nèi)部使用。

此時,可以指定這樣的數(shù)據(jù)字段為“純數(shù)據(jù)字段”,它們將僅僅被記錄在 this.data 中,而不參與任何界面渲染過程,這樣有助于提升頁面更新性能。

指定“純數(shù)據(jù)字段”的方法是在 Component 構(gòu)造器的 options 定義段中指定 pureDataPattern 為一個正則表達式,字段名符合這個正則表達式的字段將成為純數(shù)據(jù)字段。

代碼示例:

Component({
  options: {
    pureDataPattern: /^_/ // 指定所有 _ 開頭的數(shù)據(jù)字段為純數(shù)據(jù)字段
  },
  data: {
    a: true, // 普通數(shù)據(jù)字段
    _b: true, // 純數(shù)據(jù)字段
  },
  methods: {
    myMethod() {
      this.data._b // 純數(shù)據(jù)字段可以在 this.data 中獲取
      this.setData({
        c: true, // 普通數(shù)據(jù)字段
        _d: true, // 純數(shù)據(jù)字段
      })
    }
  }
})

上述組件中的純數(shù)據(jù)字段不會被應(yīng)用到 WXML 上:

<view wx:if="{{a}}"> 這行會被展示 </view>
<view wx:if="{{_b}}"> 這行不會被展示 </view>

組件屬性中的純數(shù)據(jù)字段

屬性也可以被指定為純數(shù)據(jù)字段(遵循 pureDataPattern 的正則表達式)。

屬性中的純數(shù)據(jù)字段可以像普通屬性一樣接收外部傳入的屬性值,但不能將它直接用于組件自身的 WXML 中。

代碼示例:

Component({
  options: {
    pureDataPattern: /^_/
  },
  properties: {
    a: Boolean,
    _b: {
      type: Boolean,
      observer() {
        // 不要這樣做!這個 observer 永遠不會被觸發(fā)
      }
    },
  }
})

注意:屬性中的純數(shù)據(jù)字段的屬性 observer 永遠不會觸發(fā)!如果想要監(jiān)聽屬性值變化,使用 數(shù)據(jù)監(jiān)聽器 代替。

從小程序基礎(chǔ)庫版本 2.10.1 開始,也可以在頁面或自定義組件的 json 文件中配置 pureDataPattern (這樣就不需在 js 文件的 options 中再配置)。此時,其值應(yīng)當寫成字符串形式:

{
  "pureDataPattern": "^_"
}

使用數(shù)據(jù)監(jiān)聽器監(jiān)聽純數(shù)據(jù)字段

數(shù)據(jù)監(jiān)聽器  可以用于監(jiān)聽純數(shù)據(jù)字段(與普通數(shù)據(jù)字段一樣)。這樣,可以通過監(jiān)聽、響應(yīng)純數(shù)據(jù)字段的變化來改變界面。

下面的示例是一個將 JavaScript 時間戳轉(zhuǎn)換為可讀時間的自定義組件。

代碼示例:

Component({
  options: {
    pureDataPattern: /^timestamp$/ // 將 timestamp 屬性指定為純數(shù)據(jù)字段
  },
  properties: {
    timestamp: Number,
  },
  observers: {
    timestamp: function () {
      // timestamp 被設(shè)置時,將它展示為可讀時間字符串
      var timeString = new Date(this.data.timestamp).toLocaleString()
      this.setData({
        timeString: timeString
      })
    }
  }
})
<view>{{timeString}}</view>


以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號