微信小程序 van-dropdown-menu
点击其他按钮,关闭van-dropdown-menu下拉框
- DropdownMenu 引入
- 页面使用
- index.wxml
- index.scss
- index.ts(重点)
- index.ts(全部)
DropdownMenu 引入
在app.json或index.json中引入组件
"usingComponents": {"van-dropdown-menu": "@vant/weapp/dropdown-menu/index","van-dropdown-item": "@vant/weapp/dropdown-item/index"
}
页面使用
下面是完成的使用步骤
index.wxml
<view class="seach-Main"><view class="class-main"><van-dropdown-menu active-color="#FFD69A" custom-class="menuMain" ><van-dropdown-itemtitle-class="ItemMain"value="{{ value1 }}" options="{{ option1 }}"bind:change="onDropDownChange" id="item"/></van-dropdown-menu></view><van-search class="search-text" background="#000000" value="{{ value }}" placeholder="请输入产品编号/名称" placeholder-style="font-size:28rpx;" clearable="true" use-action-slot left-icon="search" bind:focus="onFocusClick" bind:change="onChange" bind:search="submitHandle"><view slot="action" bind:tap="submitHandle" style="color: #FFFFFF;">搜索</view></van-search></view>
index.scss
.seach-Main {display: flex;justify-content: space-around;width: 100%;align-items: center;position: relative;.search-text {width: 100%;}.search-image {display: flex;position: absolute;width: 44rpx;left: 40rpx;image {width: 44rpx;height: 44rpx;}}}.seach-Main .van-search__content--square {background-color: var(--bannerBgColor) !important;border-radius: 10rpx 10rpx 10rpx 10rpx;border: 2rpx solid var(--bannerBgColor);}.seach-Main .cell-index--van-cell__value {text-align: left;}.seach-Main .van-field__control {color: var(--titleColor);}.seach-Main .van-cell__left-icon-wrap {color: var(--titleColor) !important;}// 选择.class-main {.menuMain {background-color: var(--mainBgColor);}.ItemMain {color: var(--titleColor);}}.van-cell {background-color: var(--bannerBgColor) !important;color: var(--titleColor) !important;border: none;}/* 样式文件 */.class-main .van-cell::after {border: none;}
上面var()都是引用的公共样式,可以换成自己项目需要的样式。
index.ts(重点)
在这里,需要实现输入框选中时,van-dropdown-menu组件需要关闭。所以在输入框组件里增加了bind:focus="onFocusClick"方法。在这个方法里面实现关闭操作。
// 输入框聚焦关闭组件onFocusClick() {this.selectComponent('#item').toggle(false);},
刚开始没注意官方文档的说明,现将该方法着重展示出来。
index.ts(全部)
Page({/*** 页面的初始数据*/data: {value1: '',option1: [{ text: '全部', value: '' },{ text: '干货', value: 'GH' },{ text: '调味', value: 'TW' },],groupType:'', // 分类searchField:'',// 输入框搜索内容
},
// 输入框聚焦关闭onFocusClick() {this.selectComponent('#item').toggle(false);},// 筛选onDropDownChange(e: any) {let index = e.detailif (index == 0 && this.data.value1 == 0) {index = ''}this.setData({'groupType': index,})},// 输入框值改变时的方法onChange(e: any) {this.setData({searchField: e.detail,});// 调用搜索接口},// 点击搜索按钮方法submitHandle() {this.selectComponent('#item').toggle(false); // 关闭弹框var vkey = this.data.value;if (vkey) {// 搜索关键字不为空时的操作} else {// 搜索关键字为空时的操作}},)}
最终效果如下:
点击其他方法,关闭van-dropdown-menu