私域电商软件及相关增值服务提供商    

免费试用
微信小程序开发组件间关系
作者: --时间: 2025-07-21 04:03:25 阅读量:

微信小程序组件间关系

1. 定义和使用组件间关系

对于复杂的自定义组件,组件之间的通讯往往比较困难。在组件定义时添加 relations 关系定义段可以解决这个问题。

示例中的 custom-ul 和 custom-li 都是自定义组件,添加如下关系定义后,它们之间的通讯就变得方便了。

// path/to/custom-ul.js
Component({
  relations: {
    './custom-li': {
      type: 'child', // 关联的目标节点应为子节点
      linked: function(target) {
        // 每次有custom-li被插入时执行,target是该节点实例对象,触发在该节点attached生命周期之后
      },
      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('path/to/custom-li')
    }
  },
  ready: function(){
    this._getAllLi()
  }
})
// path/to/custom-li.js
Component({
  relations: {
    './custom-ul': {
      type: 'parent', // 关联的目标节点应为父节点
      linked: function(target) {
        // 每次被插入到custom-ul时执行,target是custom-ul节点实例对象,触发在attached生命周期之后
      },
      linkChanged: function(target) {
        // 每次被移动后执行,target是custom-ul节点实例对象,触发在moved生命周期之后
      },
      unlinked: function(target) {
        // 每次被移除时执行,target是custom-ul节点实例对象,触发在detached生命周期之后
      }
    }
  }
})

注意:必须在两个组件定义中都加入relations定义,否则不会生效。

2. 关联一类组件

有时需要关联的是一类组件,这时可以使用 behavior 进行设置。对于 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', // 关联的目标节点应为祖先节点
    }
  }
})

在关系定义中,可以使用相同的 behavior 来代替具体的组件路径:

// path/to/custom-form.js
var customFormControls = require('./custom-form-controls')
Component({
  relations: {
    'customFormControls': {
      type: 'descendant', // 关联的目标节点应为子孙节点
      target: customFormControls
    }
  }
})

3. relations 定义段

relations

一套系统全搞定
  • 商家管理
  • 商品管理
  • 订单管理
  • 会员管理
  • 营销中心
  • 供应链入驻
  • 财务管理
  • 支付分账
  • 商城直播
免费试用
更多产品任你选
B2B2C多用户商城系统

类天猫&京东模式系统

了解更多
B2B2B电商交易系统

全渠道订货/采购及经销商管
理数字化系统

了解更多
S2B2B电商交易系统

上下游资源整合数字化解决方

了解更多
企业集采商城系统

中大型企业数字化采购与交易
系统

了解更多
员工福利商城系统

集福利管理、发放于一体的员
工福利商城

了解更多

电话咨询 微信咨询 0元开店