美文网首页
2、微信小程序自定义组件

2、微信小程序自定义组件

作者: 圆梦人生 | 来源:发表于2021-02-23 17:27 被阅读0次

从小程序基础库版本 [1.6.3] 开始,小程序支持简洁的组件化编程。所有自定义组件相关特性都需要基础库版本 [1.6.3] 或更高。

开发者可以将页面内的功能模块抽象成自定义组件,以便在不同的页面中重复使用;也可以将复杂的页面拆分成多个低耦合的模块,有助于代码维护。自定义组件在使用时与基础组件非常相似。

  • 创建自定义组件
    类似于页面,一个自定义组件由 json wxml wxss js 4个文件组成。要编写一个自定义组件,首先需要在 json 文件中进行自定义组件声明(将 component 字段设为 true 可将这一组文件设为自定义组件):
{
  "component": true
}
  • 使用自定义组件
    使用已注册的自定义组件前,首先要在页面的 json 文件中进行引用声明。此时需要提供每个自定义组件的标签名和对应的自定义组件文件路径:
{
  "usingComponents": {
    "component-tag-name": "path/to/the/custom/component"
  }
}
  • 触发事件
    自定义组件触发事件时,需要使用 triggerEvent 方法,指定事件名、detail对象和事件选项:
this.triggerEvent('事件名', {name: this.data.name, title: this.data.title}, {})
  • 获取组件实例
    可在父组件里调用 this.selectComponent ,获取子组件的实例对象。(插件的自定义组件将返回 null)

调用时需要传入一个匹配选择器 selector,如:this.selectComponent(".my-component")。

<custHeader class="custHeader" />

console.log('查找的组件=custHeader', this.selectComponent('.custHeader'));

完整案例

  • pages/pagea/pagea.wxml
<custHeader class="custHeader" bindheaderclick="headerclickfun" name="zhangsanname" title="{{cmptitle}}"/>
  • pages/pagea/pagea.json
{
  "usingComponents": {
    "custHeader": "../components/top"
  }
}
  • pages/pagea/pagea.js
Page({
  data: {
   cmptitle: 'defaulttitle'
  },
  headerclickfun(e){
    console.log('header组件传的事件', e);
  },
  onReady: function () {
    console.log('查找的组件=custHeader', this.selectComponent('.custHeader'));
  }
})
  • pages/components/top.wxml
<text>
  {{msg}}  == {{name}} == {{title}}
</text>
 <button bindtap="headertp">点击</button>
  • pages/components/top.json
{
  "component": true
}

相关文章

网友评论

      本文标题:2、微信小程序自定义组件

      本文链接:https://www.haomeiwen.com/subject/lrzrfltx.html