Search 搜索

引入

app.jsonindex.json中引入组件,详细介绍见快速上手

  1. "usingComponents": {
  2. "van-search": "path/to/@vant/weapp/dist/search/index"
  3. }

代码演示

基础用法

van-search 中,value 用于控制搜索框中的文字。background 可以自定义搜索框外部背景色。

  1. <van-search value="{{ value }}" placeholder="请输入搜索关键词" />

监听对应事件

van-search 提供了 search 和 cancel 事件。search 事件在用户点击键盘上的搜索按钮触发。cancel 事件在用户点击搜索框右侧取消按钮时触发

  1. <van-search
  2. value="{{ value }}"
  3. placeholder="请输入搜索关键词"
  4. show-action
  5. bind:search="onSearch"
  6. bind:cancel="onCancel"
  7. />

自定义行动按钮

van-search 支持自定义右侧取消按钮,使用名字为 action 的 slot,并设置 use-action-slot 为 true 即可。

  1. <van-search
  2. value="{{ value }}"
  3. placeholder="请输入搜索关键词"
  4. use-action-slot
  5. bind:change="onChange"
  6. bind:search="onSearch"
  7. >
  8. <view slot="action" bind:tap="onClick">搜索</view>
  9. </van-search>
  1. Page({
  2. data: {
  3. value: ''
  4. },
  5. onChange(e) {
  6. this.setData({
  7. value: e.detail
  8. });
  9. },
  10. onSearch() {
  11. Toast('搜索' + this.data.value);
  12. },
  13. onClick() {
  14. Toast('搜索' + this.data.value);
  15. },
  16. });

API

Props

参数说明类型默认值版本
name在表单内提交时的标识符string--
label搜索框左侧文本string--
shape形状,可选值为 roundstringsquare-
value当前输入的值string | number--
background搜索框背景色string#f2f2f2-
show-action是否在搜索框右侧显示取消按钮booleanfalse-
action-text取消按钮文字boolean取消1.0.0
focus获取焦点booleanfalse-
error是否将输入内容标红booleanfalse-
disabled是否禁用输入框booleanfalse-
readonly是否只读booleanfalse-
clearable是否启用清除控件booleantrue-
maxlength最大输入长度,设置为 -1 的时候不限制最大长度number-1-
use-action-slot是否使用 action slotbooleanfalse-
placeholder输入框为空时占位符string--
placeholder-style指定占位符的样式string--
input-align输入框内容对齐方式,可选值为 center rightstringleft-
use-left-icon-slot是否使用输入框左侧图标 slotbooleanfalse-
use-right-icon-slot是否使用输入框右侧图标 slotbooleanfalse-
left-icon输入框左侧图标名称或图片链接,可选值见 Icon 组件(如果设置了use-left-icon-slot,则该属性无效)stringsearch-
right-icon输入框右侧图标名称或图片链接,可选值见 Icon 组件(如果设置了use-right-icon-slot,则该属性无效)string--

Events

事件名说明参数
bind:search确定搜索时触发event.detail: 当前输入值
bind:change输入内容变化时触发event.detail: 当前输入值
bind:cancel取消搜索搜索时触发-
bind:focus输入框聚焦时触发-
bind:blur输入框失焦时触发-
bind:clear点击清空控件时触发-

Slot

名称说明
action自定义搜索框右侧按钮,需要在use-action-slot为 true 时才会显示
label自定义搜索框左侧文本
left-icon自定义输入框左侧图标,需要在use-left-icon-slot为 true 时才会显示
right-icon自定义输入框右侧图标,需要在use-right-icon-slot为 true 时才会显示

外部样式类

类名说明
custom-class根节点样式类
field-class搜索框样式类
input-class输入框样式类
cancel-class取消按钮样式类

Search 搜索 - 图1