一、源码地址
https://github.com/imxiaoer/WeChatMiniSelect
二、效果图
录屏图片质量较差,所以大家会看到残影(捂脸)
三、组件源码
1. select.wxml
说明:用 catchtap 而不用 bindtap 是为了阻止事件冒泡,为了实现点击页面其他地方关闭 select, 所以在父页面(index.wxml)最外层绑定了 bindtap="close" 方法, 不阻止冒泡的话会执行父组件的 close 方法
2. select.js
Component({ properties: { options: { type: Array, value: [] }, defaultOption: { type: Object, value: { id: '000', name: '全部城市' } }, key: { type: String, value: 'id' }, text: { type: String, value: 'name' } }, data: { result: [], isShow: false, current: {} }, methods: { optionTap(e) { let dataset = e.target.dataset this.setData({ current: dataset, isShow: false }); // 调用父组件方法,并传参 this.triggerEvent("change", { ...dataset }) }, openClose() { this.setData({ isShow: !this.data.isShow }) }, // 此方法供父组件调用 close() { this.setData({ isShow: false }) } }, lifetimes: { attached() { // 属性名称转换, 如果不是 { id: '', name:'' } 格式,则转为 { id: '', name:'' } 格式 let result = [] if (this.data.key !== 'id' || this.data.text !== 'name') { for (let item of this.data.options) { let { [this.data.key]: id, [this.data.text]: name } = item result.push({ id, name }) } } this.setData({ current: Object.assign({}, this.data.defaultOption), result: result }) } }})说明:properties中的 key 和 text 是为了做属性名转换。比如我现在的数据结构如下:
[{ city_id: '001', city_name: '北京' }, { city_id: '002', city_name: '上海' }, { city_id: '003', city_name: '深圳' }]而 select 组件要求的数据结构是:
因此我们就要将 city_id 转换成 id,city_name 转换成 name。 怎么实现属性名转换呢? 就是通过 key 和 text 这两个参数。
3. select.json
{ "component": true, "usingComponents": {}}4. select.wxss
四、组件的使用
index.wxml
<view class="container" bindtap="close"> <view class="select-wrap"> <select id="select" options="{{options}}" key="city_id" text="city_name" bind:change="change"></select> </view></view>总结
以上所述是小编给大家介绍的微信小程序 select 下拉框组件功能,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对网站的支持!
如果你觉得本文对你有帮助,欢迎转载,烦请注明出处,谢谢!