前言
relations 定义段包含目标组件路径及其对应选项,可包含的选项见下表。
一、组件间关系
有时需要实现这样的组件:
1.index页面
{ "usingComponents": { "custom-ul": "/components/custom-ul-component", "custom-li": "/components/custom-li-component" } }
<custom-ul> <custom-li> item 1 </custom-li> <custom-li> item 2 </custom-li> </custom-ul>
2.custom-ul
// path/to/custom-ul.js Component({ relations: { './custom-li-component': { type: 'child', // 关联的目标节点应为子节点 linked: function (target) { // 每次有custom-li被插入时执行,target是该节点实例对象,触发在该节点attached生命周期之后 console.log('[custom-ul] a child is linked: ', target) }, linkChanged: function (target) { // 每次有custom-li被移动后执行,target是该节点实例对象,触发在该节点moved生命周期之后 }, unlinked: function (target) { // 每次有custom-li被移除时执行,target是该节点实例对象,触发在该节点detached生命周期之后 } } }, methods: { _getAllLi: function () { // 使用getRelationNodes可以获得nodes数组,包含所有已关联的custom-li,且是有序的 var nodes = this.getRelationNodes('./custom-li-component') console.log(nodes) } }, ready: function () { this._getAllLi() } })
<!-- 组件模板 --> <view class="wrapper"> <slot></slot> </view>
3.custom-ul
// path/to/custom-li.js Component({ relations: { './custom-ul-component': { type: 'parent', // 关联的目标节点应为父节点 linked: function (target) { // 每次被插入到custom-ul时执行,target是custom-ul节点实例对象,触发在attached生命周期之后 console.log('child linked to ', target) }, linkChanged: function (target) { // 每次被移动后执行,target是custom-ul节点实例对象,触发在moved生命周期之后 }, unlinked: function (target) { // 每次被移除时执行,target是custom-ul节点实例对象,触发在detached生命周期之后 } } } })
<text> li </text>
二、关联一类组件
1.index页面
{ "usingComponents": { "custom-input": "../components/custom-input", "custom-submit": "../components/custom-submit", "custom-form": "../components/custom-form" } }
<custom-form> <view> input <custom-input></custom-input> </view> <custom-submit> submit </custom-submit> </custom-form>
// path/to/custom-form-controls.js module.exports = Behavior({ // ... })
2.custom-form
var customFormControls = require('./custom-form-controls') Component({ relations: { 'customFormControls': { type: 'descendant', // 关联的目标节点应为子孙节点 target: customFormControls, linked: function(target) { console.info('已关联到 ' + target.is) } } } })
3.custom-input
// path/to/custom-input.js var customFormControls = require('./custom-form-controls') Component({ behaviors: [customFormControls], relations: { './custom-form': { type: 'ancestor', // 关联的目标节点应为祖先节点 } } })
4.custom-form
// path/to/custom-submit.js var customFormControls = require('./custom-form-controls') Component({ behaviors: [customFormControls], relations: { './custom-form': { type: 'ancestor', // 关联的目标节点应为祖先节点 } } })