微信小程序的關(guān)聯(lián)relations 基本用法

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

1、直接引用組件


子組件.png

父組件.png

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

2、關(guān)聯(lián)一類組件
例如:

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

custom-form 組件想要關(guān)聯(lián) 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', // 關(guān)聯(lián)的目標節(jié)點應(yīng)為祖先節(jié)點
    }
  }
})
// path/to/custom-submit.js
var customFormControls = require('./custom-form-controls')
Component({
  behaviors: [customFormControls],
  relations: {
    './custom-form': {
      type: 'ancestor', // 關(guān)聯(lián)的目標節(jié)點應(yīng)為祖先節(jié)點
    }
  }
})

則在 relations 關(guān)系定義中,可使用這個behavior來代替組件路徑作為關(guān)聯(lián)的目標節(jié)點:

// path/to/custom-form.js
var customFormControls = require('./custom-form-controls')
Component({
  relations: {
    'customFormControls': {
      type: 'descendant', // 關(guān)聯(lián)的目標節(jié)點應(yīng)為子孫節(jié)點
      target: customFormControls
    }
  }
})

產(chǎn)生關(guān)聯(lián)關(guān)系后,需要在有些時候獲取到父組件或子組件以獲取組件的數(shù)據(jù),這時候通常使用getRelationNodes()方法獲取。

獲取父組件,在調(diào)用getRelationNodes時傳遞父組件的路徑

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

推薦閱讀更多精彩內(nèi)容