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

微信小程序自定义组件

作者: 随烟灬 | 来源:发表于2020-12-17 17:23 被阅读0次

先附上微信小程序组件封装官方指南地址

一、如何创建组件

  • 在根目录创建components存放组件


    WX20201217-165921.png
  • 编写组件的布局与样式
<!--component/bottomBtn.wxml-->
<view class='fixed-bottom-height'></view>
<view class="fixed-bottom-btn {{showCancel ? 'two':''}}">
    <block wx:if="{{showCancel}}">
        <button bindtap="tapCancel" class='btn-gray' style="padding-bottom: {{iphone_tag ? 68:0}}rpx;">{{cancelText}}</button>
    </block>
    <button class="bg-blue" bindtap="touchSubmitBtn" loading="{{loading}}" disabled="{{disabled}}" style="padding-bottom: {{iphone_tag ? 68:0}}rpx;">{{btnText}}</button>
</view>
.fixed-bottom-height {
  height: 200rpx;
}
.fixed-bottom-btn {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 0rpx;
  background-color: white;
  border-top: 2rpx solid #f1f1f1;
  z-index: 100;
  font-size: 0;
}
.fixed-bottom-btn button {
  font-size: 36rpx;
  border-radius: 0rpx;
  padding-top: 20rpx;
  min-height: 130rpx;
}
.fixed-bottom-btn.two button {
  display: inline-block;
  width: 50%; 
}
.fixed-bottom-btn.two button.reject {
  background-color: #e0e0e0 !important;
}
.bg-blue{
  background-color: #418ef6 !important;
  color: white;
  border-color: #418ef6;
}
  • 组件的js
// component/bottomBtn.js
Component({
  /**
   * 组件的属性列表
   */
  properties: {
    btnText: {
      type: String,
      value: '提交'
    },
    loading: {
      type: Boolean,
      value: false
    },
    disabled: {
      type: Boolean,
      value: false
    },
    showCancel: {
      type: Boolean,
      value: false
    },
    cancelText: {
      type: String,
      value: '删除'
    }
  },

  /**
   * 组件的初始数据
   */
  data: {

  },
  /**
   * 组件的方法列表
   */
  methods: {
    // 提交按钮
    touchSubmitBtn() {
      this.triggerEvent('save')
    },
    /**
     * 删除/取消
     */
    tapCancel() {
      this.triggerEvent('cancel')
    }
  }
})

二、如何使用组件

  • 在页面.json文件引入
"usingComponents": {
  "bottom-btn": "/component/bottomBtn/bottomBtn"
}
  • wxml使用组件
<bottom-btn btnText="确定"  bind:save="tapConfirm"></bottom-btn>
  • js执行方法
tapConfirm() {
  // do something
}

相关文章

网友评论

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

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