自定义一个下拉框组件custom-drop-down
1. custom-drop-down.wxml
<view class="drop-container bg-gradual-blue">
<view class="dorp-fix">
<view class="drop-main" bindtap="clickShow">
<view>{{provinceValue}}</view>
<image src="{{show ? '../../../images/caret-up-s.png':'../../../images/caret-down-s.png'}}" class="dropdown-img"></image>
</view>
<view class="list-style bg-gradual-gray" wx:if="{{show}}">
<cover-view class="option_list" wx:if="{{show}}">
<cover-view bindtap="onChangeOrder" data-index="{{index}}" class="list-item" wx:for="{{orderOption}}" wx:key="value">{{item.text}}</cover-view>
</cover-view>
</view>
</view>
</view>
2. custom-drop-down.wxss
.drop-container {
position: relative;
display: flex;
flex-direction: column;
top:0;
left: 0;
height: 30px;
line-height: 30px;
margin: 0 20px;
border-radius: 10px;
}
.drop-main {
display: flex;
justify-content: center;
align-items: center;
}
.dropdown-img {
width: 20px;
height: 20px;
margin-left: 5px;
}
.list-style{
position: absolute;
z-index: 100;
width: 100%;
/* background-color: greenyellow; */
top: 30px;
border-radius: 10px;
box-sizing: border-box;
}
.option_list{
height: 60px;
}
.list-item{
display: flex;
align-items: center;
justify-content: center;
height: 30px;
border-bottom: 1px solid #fff;
}
3.custom-drop-down.js
// colorui/components/custom-drop-down.js
const app = getApp()
Component({
/**
* 组件的属性列表
*/
properties: {
orderOption: {
type: Array,
value: [{
text: '默认排序',
value: 'a'
},
{
text: '名称排序',
value: 'b'
}
]
},
show: {
type: Boolean,
value: false
},
selectData: {
type: Object,
value: {}
},
},
// 解决组件中样式无效的问题
options: {
addGlobalClass: true
},
/**
* 组件的初始数据
*/
data: {
provinceValue: '默认排序'
},
/**
* 组件的方法列表
*/
methods: {
// 点击改变show取值
clickShow() {
this.setData({
show: !this.data.show
})
},
// 改变查询项
onChangeOrder(e) {
const orderIndex = e.currentTarget.dataset.index
for (let i = 0; i < this.data.orderOption.length; i++) {
let item = this.data.orderOption[i]
if (i === orderIndex) {
item.selected = true
} else {
item.selected = false
}
}
this.setData({
provinceValue: this.data.orderOption[orderIndex].text,
orderOption: this.data.orderOption,
show: !this.data.show
})
this.triggerEvent('getValue', this.data.orderOption[orderIndex])
},
// 选择后改变值
selectedValue(name) {
for (let i = 0; i <= this.data.orderOption.length; i++) {
let item = this.data.orderOption[i]
if (item.text == name) {
item.selected = true
} else {
item.selected = false
}
}
this.setData({
orderOption: this.data.orderIndex
})
}
},
// 若不写在lifetime节点中且同时存在lifetime节点,优先执行lifetime节点中的生命周期函数,并覆盖掉节点之外的生命周期函数
lifetimes: {
attached() {
if (Object.keys(this.data.selectData).length !== 0) {
this.selectedValue(this.data.selectData.text)
this.setData({
provinceValue: this.data.selectData.text
})
}
}
}
})
使用组件custom-drop-down
<custom-drop-down bindgetValue="getWayValue"/>
结果展示: