小程序自定义组件库

面向微信小程序的可复用组件实践:评分组件、防抖按钮,含 WXML/JS 完整实现与使用方式。

场景:组件复用 技术栈:微信小程序原生组件 来源:GitHub 参考

代码示例:评分组件

js
// components/rating/rating.js —— 可复用评分组件
Component({
  properties: {
    value: { type: Number, value: 0 },   // 当前分数
    max:   { type: Number, value: 5 },   // 满分
    size:  { type: Number, value: 24 }   // 星号尺寸 rpx
  },
  data: { list: [1, 2, 3, 4, 5] },
  methods: {
    onTap(e) {
      const n = e.currentTarget.dataset.n;
      this.setData({ value: n });
      this.triggerEvent("change", { value: n });
    }
  }
});
wxml
<!-- components/rating/rating.wxml -->
<view class="rating" role="radiogroup">
  <view wx:for="{{list}}" wx:key="*this"
        class="star {{item <= value ? 'on' : ''}}"
        data-n="{{item}}" bindtap="onTap"
        style="width:{{size}}rpx;height:{{size}}rpx;font-size:{{size}}rpx">
    ★
  </view>
</view>
js
// components/debounce-btn/debounce-btn.js —— 防抖按钮
Component({
  properties: { text: { type: String, value: "提交" } },
  data: { locked: false },
  methods: {
    onTap() {
      if (this.data.locked) return;      // 已锁定则忽略
      this.setData({ locked: true });    // 300ms 内防重入
      this.triggerEvent("tap");
      setTimeout(() => this.setData({ locked: false }), 300);
    }
  }
});

操作步骤

  1. components/rating/ 目录创建 rating.json 声明组件,rating.wxml/js/wxss 实现。
  2. 页面 usingComponents 注册后即可 <rating value="4"> 使用。
  3. 评分变化通过 triggerEvent("change") 通知父页面。
  4. 防抖按钮组件避免支付/提交被重复点击。

来源参考

GitHub 关键词:weapp-componentsminiprogram-custom-componentweui-miniprogram