微信小程序的關聯relations 基本用法

在小程序中可以通過relations字段建立組件間的關系,即關聯。這個關系是祖先和后代的關系。
小程序中實現組件關聯的方式,主要是通過relations字段,表現形式為兩種。

1、直接引用組件


子組件.png

父組件.png

必須在兩個組件定義中都加入relations定義,否則不會生效。

2、關聯一類組件
例如:

<custom-form>
  <view>
    input
    <custom-input></custom-input>
  </view>
  <custom-submit> submit </custom-submit>
</custom-form>

custom-form 組件想要關聯 custom-input 和 custom-submit 兩個組件。此時,如果這兩個組件都有同一個behavior:

// path/to/custom-form-controls.js
module.exports = Behavior({
  // ...
})
// path/to/custom-input.js
var customFormControls = require('./custom-form-controls')
Component({
  behaviors: [customFormControls],
  relations: {
    './custom-form': {
      type: 'ancestor', // 關聯的目標節點應為祖先節點
    }
  }
})
// path/to/custom-submit.js
var customFormControls = require('./custom-form-controls')
Component({
  behaviors: [customFormControls],
  relations: {
    './custom-form': {
      type: 'ancestor', // 關聯的目標節點應為祖先節點
    }
  }
})

則在 relations 關系定義中,可使用這個behavior來代替組件路徑作為關聯的目標節點:

// path/to/custom-form.js
var customFormControls = require('./custom-form-controls')
Component({
  relations: {
    'customFormControls': {
      type: 'descendant', // 關聯的目標節點應為子孫節點
      target: customFormControls
    }
  }
})

產生關聯關系后,需要在有些時候獲取到父組件或子組件以獲取組件的數據,這時候通常使用getRelationNodes()方法獲取。

獲取父組件,在調用getRelationNodes時傳遞父組件的路徑

直接引用時使用.png
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容