微信小程序自定义组件

1.父组件引用自定义组件:

在父组件的.json文件中:

"usingComponents": {
    "my-comp": "/components/myComp/index",
 }
在父组件的.wxml文件中
<view>
<my-comp bindchange="changeValue"></my-comp>
</view>

2.父组件向子组件传参,使用properties传参:

使用方式和vue的方式一样;

3.子组件向父组件传参,使用this.triggerEvent:

子组件向父组件传参:

this.triggerEvent('change', event.currentTarget.dataset.text)
父组件接收, wxml部分:
<view>
<my-comp bindchange="changeValue"></my-comp>
 
</view>
js部分:
changeValue(e){
  console.log("拿到信息", e.detail); // e.detail就是子组件的event.currentTarget.dataset.text
}
4.自定义组件的生命周期:
/**
   * 组件的初始数据
   */
  data: {
    page: 1, // 第一页
  },
  /**
   * 组件的生命周期
  */
  lifetimes: {
    /**
     * 组件实例刚刚被创建好时, created 生命周期被触发
     * 通常情况下,这个生命周期只应该用于给组件 this 添加一些自定义属性字段。
     */
    created: function(){},
    /**
     * 在组件实例进入页面节点树时执行
     * 这个生命周期很有用,绝大多数初始化工作可以在这个时机进行
     */
    attached: function() {},
    /**
     * 在组件实例被从页面节点树移除时执行
     * 退出一个页面时,如果组件还在页面节点树中,则 detached 会被触发
     */
    detached: function() {
      //---------
    },
  }
posted @ 2024-01-24 03:37  海底流  阅读(59)  评论(0编辑  收藏  举报