温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

微信小程序组件间关系怎么定义和使用

发布时间:2022-03-07 10:22:01 来源:亿速云 阅读:165 作者:iii 栏目:开发技术

这篇文章主要介绍“微信小程序组件间关系怎么定义和使用”的相关知识,小编通过实际案例向大家展示操作过程,操作方法简单快捷,实用性强,希望这篇“微信小程序组件间关系怎么定义和使用”文章能帮助大家解决问题。

  组件间关系

  定义和使用组件间关系

  有时需要实现这样的组件:

  item 1

  item 2

  这个例子中, custom-ul 和 custom-li 都是自定义组件,它们有相互间的关系,相互间的通信往往比较复杂。此时在组件定义时加入 relations 定义段,可以解决这样的问题。示例:

  // 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定义,否则不会生效。

  关联一类组件

  有时,需要关联的是一类组件,如:

  

  

  input

  

  submit

  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

  }

  }

  })

关于“微信小程序组件间关系怎么定义和使用”的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识,可以关注亿速云行业资讯频道,小编每天都会为大家更新不同的知识点。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI