11.10 学几行代码撸一个微信小程序组件,利用你的想象,秒变大神

学几行代码撸一个微信小程序组件,利用你的想象,秒变大神

使用方式

配置 json:

"usingComponents": {
"z-checkbox":"../../my_component/checkbox/index"
}

调用:


checkList 数据格式:

payTypeList:[
{ label: "微信", value: "wechat"},
{ label: "支付宝", value: "alipay"},
]

属性

学几行代码撸一个微信小程序组件,利用你的想象,秒变大神

属性 说明 类型 默认

checkList 列表: label(文字) value(返回值) Array []

width 宽度,默认185rpx Number String 185

事件

学几行代码撸一个微信小程序组件,利用你的想象,秒变大神

事件名 说明 返回值

bind:change 点击时的回调,返回所选中的value ["wechat","alipay"]

代码实现

  • 新建目录,在目录中新建Component文件
  • 目录结构
学几行代码撸一个微信小程序组件,利用你的想象,秒变大神

js部分:

Component({
properties: {
// checkbox列表
checkList:{
type: Array,
value:[]
},
// checkbox的宽度
width:{
type:[Number,String],
value:185
},
},
data: {
// 选中的值
activeList:[],
},
methods: {
// 点击check触发的事件
clickCheck(e){
// 获取被点击的value
let value = e.currentTarget.dataset.value;
let activeList = this.data.activeList;
// 判断被点击的value是否在选中的数组中
let haveValue = activeList.indexOf(value);
if (haveValue == -1){
// 不存在时加入
activeList.push(value)
}else{
// 存在时清除
activeList.splice(haveValue,1)
}
// 设置到data中
this.setData({
activeList: activeList
})
// 提交回调给父级,并携带选中的值
this.triggerEvent('change', activeList);
},
}

})

wxss部分:

view{
box-sizing: border-box;
}
.check_list_style{
height: 82rpx;
line-height: 82rpx;
width: 185rpx;
text-align: center;
background: #F5F5F7;
color:#000;
border-radius: 5rpx;
margin-right:20rpx;
display: inline-block;
transition: all .3s;
}
.active_style{
background: #D8E5FA;
color:#3B7DE7;
}

wxs部分:

  • 要知道数组中存在哪些value来判断对应checkbox高亮,这里借助了 wxs 文件,在当前目录创建 index.wxs
/**
* 接收两个参数
* item (当前节点的value)
* list (选中的value的数组)
**/

function active(item,list){
//判断数组中是否已存在相同value,存在返回true,不存在返回fase

var index = list.indexOf(item);
var active = index == -1 ? false : true
return active
}

module.exports = {
active: active
}

wxml部分:




{{item.label}}


我自己是一名从事了多年的前端老程序员,小编为大家准备了新出的前端编程学习资料,免费分享给大家!

如果你也想学习前端,那么帮忙转发一下然后再关注小编后私信【1】可以得到我整理的这些前端资料了(私信方法:点击我头像进我主页有个上面有个私信按钮)


分享到:


相關文章: