<custom-ul><custom-li>item 1</custom-li><custom-li>item 2</custom-li></custom-ul>
custom-ul
和custom-li
都是自定义组件,它们有相互间的关系,相互间的通信往往比较复杂。此时在组件定义时加入relations
定义段,可以解决这样的问题。// path/to/custom-ul.jsComponent({relations: {'./custom-li': {type: 'child', // 关联的目标节点应为子节点linked(target) {// 每次有custom-li被插入时执行,target是该节点实例对象,触发在该节点attached生命周期之后},linkChanged(target) {// 每次有custom-li被移动后执行,target是该节点实例对象,触发在该节点moved生命周期之后},unlinked(target) {// 每次有custom-li被移除时执行,target是该节点实例对象,触发在该节点detached生命周期之后}}},methods: {_getAllLi() {// 使用getRelationNodes可以获得nodes数组,包含所有已关联的custom-li,且是有序的const nodes = this.getRelationNodes('path/to/custom-li')}},ready() {this._getAllLi()}})
// path/to/custom-li.jsComponent({relations: {'./custom-ul': {type: 'parent', // 关联的目标节点应为父节点linked(target) {// 每次被插入到custom-ul时执行,target是custom-ul节点实例对象,触发在attached生命周期之后},linkChanged(target) {// 每次被移动后执行,target是custom-ul节点实例对象,触发在moved生命周期之后},unlinked(target) {// 每次被移除时执行,target是custom-ul节点实例对象,触发在detached生命周期之后}}}})
<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.jsmodule.exports = Behavior({// ...})
// path/to/custom-input.jsconst customFormControls = require('./custom-form-controls')Component({behaviors: [customFormControls],relations: {'./custom-form': {type: 'ancestor', // 关联的目标节点应为祖先节点}}})
// path/to/custom-submit.jsconst customFormControls = require('./custom-form-controls')Component({behaviors: [customFormControls],relations: {'./custom-form': {type: 'ancestor', // 关联的目标节点应为祖先节点}}})
relations
关系定义中,可使用这个 behavior 来代替组件路径作为关联的目标节点:// path/to/custom-form.jsconst customFormControls = require('./custom-form-controls')Component({relations: {customFormControls: {type: 'descendant', // 关联的目标节点应为子孙节点target: customFormControls}}})
relations
定义段包含目标组件路径及其对应选项,可包含的选项见下表。选项 | 类型 | 是否必填 | 描述 |
type | string | 是 | 目标组件的相对关系,可选的值为 parent 、 child 、 ancestor 、 descendant |
linked | function | 否 | 关系生命周期函数,当关系被建立在页面节点树中时触发,触发时机在组件 attached 生命周期之后 |
linkChanged | function | 否 | 关系生命周期函数,当关系在页面节点树中发生改变时触发,触发时机在组件 moved 生命周期之后 |
unlinked | function | 否 | 关系生命周期函数,当关系脱离页面节点树时触发,触发时机在组件 detached 生命周期之后 |
target | string | 否 | 如果这一项被设置,则它表示关联的目标节点所应具有的behavior,所有拥有这一 behavior 的组件节点都会被关联 |
本页内容是否解决了您的问题?