微信小程序 自定义组件 select下拉选择器
首先我们自定义组件需要了解一下微信小程序如何自定义组件
在你的项目文件里新建一个components的文件夹
我这里建立在 pages里了 其实最好建立在和pages同级
然后在components文件夹里新建一个你组件的文件夹和内容
右键创建Component
这样就创建好了
然后我们把相应的代码放进去
wxml代码
<view class='select_box'>
<view class='select' catchtap='selectTap'>
<text class='select_text'>{{listData[index]}}</text>
<image class='select_img {{selectShow&&"select_img_rotate"}}' src='../../images/b2.png' background-size="contain">
</image>
</view>
<view class='option_box' wx:if="{{selectShow}}"
style='height:{{selectShow?(listData.length>5?325:listData.length*50):0}}rpx;'>
<text class='option' wx:for='{{listData}}' wx:key='index' data-index='{{index}}'
catchtap='optionTap'>{{item}}</text>
</view>
</view>
css代码
/* pages/components/selector/selector.wxss */
.select_box {
background: #fff;
width: 300rpx;
height: 50rpx;
border-radius: 14rpx;
position: relative;
border: 1px solid #ccc;
z-index: 10;
}
.select_box .select {
box-sizing: border-box;
width: 100%;
height: 100%;
border-radius: 8rpx;
display: flex;
align-items: center;
padding: 0 10rpx;
}
.select_box .select .select_text {
font-size: 26rpx;
color: #777777;
line-height: 28rpx;
flex: 1;
}
.select_box .select .select_img {
width: 30rpx;
height: 30rpx;
display: block;
transition: transform 0.3s;
}
.select_box .select .select_img_rotate {
transform: rotate(180deg);
}
.select_box .option_box {
position: absolute;
top: 50rpx;
left: 0;
width: 100%;
box-sizing: border-box;
height: 0;
overflow-y: auto;
background: #fff;
transition: height 0.3s;
border-left: 1px solid #efefef;
border-right: 1px solid #efefef;
}
.select_box .option_box .option {
display: block;
line-height: 30rpx;
font-size: 26rpx;
border-top: 1px solid #efefef;
border-bottom: 1px solid #efefef;
padding: 10rpx;
}
js代码
// pages/components/selector/selector.js
Component({
/**
* 组件的属性列表
*/
properties: {
listData: {
type: Array,
value: [],
}
},
/**
* 组件的初始数据
*/
data: {
selectShow: false,
index: 0
},
/**
* 组件的方法列表
*/
methods: {
// 点击下拉显示框
selectTap() {
this.setData({
selectShow: !this.data.selectShow
});
},
// 点击下拉列表
optionTap(e) {
let Index = e.currentTarget.dataset.index; //获取点击的下拉列表的下标
this.setData({
selectShow: !this.data.selectShow,
index: Index
});
this.triggerEvent('optionTap', this.data.listData[Index])
},
}
})
json代码
{
"component": true,
"usingComponents": {}
}
然后我们写到页面上
首先我们在需要用这个组件的页面上引入组件
json
{
"component": true,
"usingComponents": {
这里写路径
"selector": "/pages/components/selector/selector"
},
"navigationBarTitleText": "交接任务"
}
然后在页面中
<selector listData="{{listData}}" bind:optionTap='chooseList'></selector>
引入 需要传递一个数组listData 和定义一个函数接选择的值
data: {
listData: [3, 2, 1],
},
//接受回传的值
chooseList(data) {
console.log(data.detail)
},
这样就好了
如果你有封装好的组件 敬请投稿
L13831467435@163.com