小程序模板:专业的小程序模板与静态模板分享平台
小程序
教程
搜索
当前位置 : 首页> 小程序教程> 微信小程序自定义组件-星星评分

微信小程序自定义组件-星星评分

小程序支持简洁的组件化编程,可以将页面内的功能模块抽象成自定义组件,以便在不同的页面中复用,提高自己代码的可读性,降低自己维护代码的成本!



  
  
// components/star/star.js
Component({
  /**
   * 组件的属性列表
   * 用于组件自定义设置
   */
  properties: {
    total: { // 星星总数
      type: Number, // 类型(必填),目前接受的类型包括:String, Number, Boolean, Object, Array, null(表示任意类型)
      value: 1 // 属性初始值(可选),如果未指定则会根据类型选择一个
    },
    num: { // 点亮的星星个数
      type: Number,
      value: 1,
      observer: function(val){ // 重要!! 数据改变时调用的方法
        this.setData({
          Anum1: new Array(val > this.properties.total ? this.properties.total : val),
          Anum2: new Array(this.properties.total - val >= 0 ? this.properties.total - val : 0)
        })
      }
    }
  },

  /**
   * 组件的初始数据
   * 可用于模版渲染
   */
  data: {
    Anum1: null,
    Anum2: null
  },

  ready: function() {
    this.setData({
      Anum1: new Array(this.properties.num),
      Anum2: new Array(this.properties.total - this.properties.num)
    })
  }

})
/* components/star/star.wxss */
.star{
  height: 100%;
  display: flex;
  align-items: center;
}
.icon-star{
  margin: 0 2rpx; 
  width: 32rpx;
  height: 32rpx;
}


使用

// 在使用页面的json文件中注册
// index.json 
{
  "usingComponents": {
    "star": "../../components/star/star"
  }
}

// index.wxml

  


// index.js
this.setData({
  total: 3,
  num: 1
})

// index.wxss
.box {
  padding: 0 10rpx;
  height: 44rpx;
  line-height: 44rpx;
  text-align: center;
  font-size: 28rpx;
  border-radius: 22rpx;
  background-color: rgb(95, 140, 206);
  box-shadow: inset 0 -2rpx 0 0 rgb(77, 119, 182);
}

联系客服 意见反馈

签到成功!

已连续签到1天,签到3天将获得积分VIP1天

知道了