小程序自定义组件

  • 创建组件

  • 页面引入组件

在页面的json中添加组件

  "usingComponents": {
    "custombar": "../../components/custombar/custombar"
  },

在页面的wxml中添加组件

  <custombar></custombar>
  • 页面向组件传值

在组件的js中,向properties添加接收传值的属性

// components/custombar.js
Component({
  /**
   * 组件的属性列表
   */
  properties: {
    title: String
  },
})

页面的wxml中在组件标签上直接写需要传递的值

<custombar title="hello"></custombar>

组件的wxml中将传进来的值展示

<text>{{title}}</text>
  • 组件的自定义事件

组件添加点击事件

<view class="button" bindtap="shareClick">点击事件</view>

点击事件里注册自定义事件 this.triggerEvent(“myevent”, {data:‘子组件像父页面传递的参数’});

Component({

  ...

  /**
   * 组件的方法列表
   */
  methods: {
    shareClick: function(e) {
      console.log("shareClick");
      this.triggerEvent("share", {data: 'share'});
    },
  }
})

在页面引入的组件标签上绑定自定义事件

<custombar bindshare="shareClick2" title="分享"/>

页面处理组件传递过来的参数

Page({

  ...

  shareClick2: function(e) {
    console.log(e.detail);
    console.log('shareClick');
  }
})
  •  页面form提交获取组件的值

设置behaviors为wx://form-field 可以使自定义组件有类似于表单控件的行为。

组件添加behaviors和value属性

Component({
  behaviors: ['wx://form-field'],

  properties: {
    value: String,
  },

 组件wxml提交form

<form bindsubmit="buttonClick">
    <custombar title="hello" value="{{username}}"></custombar>
    <button class="button" formType="submit">提交</button>
</form>

即可拿到组件的value

buttonClick: function (e) {
    let params = e.detail.value
    console.log(params)
}
  • 页面调用组件方法

组件定义方法

Component({
  methods: {
    showDialog: function () {
      this.setData({
        isShowDialog: true,
      });
    },
  }
})

页面WXML

<custombar id="custombar" />

 页面JS

manageClick: function (e) {
  let component = this.selectComponent('#custombar')
  component.showDialog();
},

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值