From 2833bc03f5243370e5a3aeece5b823fc2ebde64c Mon Sep 17 00:00:00 2001 From: chenjiahan Date: Sat, 21 Nov 2020 18:59:57 +0800 Subject: [PATCH] feat(Search): add focus method --- src/search/README.md | 8 ++++++++ src/search/README.zh-CN.md | 8 ++++++++ src/search/index.js | 16 ++++++++++++++++ types/index.d.ts | 3 ++- types/search.d.ts | 5 +++++ 5 files changed, 39 insertions(+), 1 deletion(-) create mode 100644 types/search.d.ts diff --git a/src/search/README.md b/src/search/README.md index d20e011a2..e3bb949f4 100644 --- a/src/search/README.md +++ b/src/search/README.md @@ -141,6 +141,14 @@ Use `action` slot to custom right button, `cancel` event will no longer be Emitt | clear | Emitted when the clear icon is clicked | _event: Event_ | | cancel | Emitted when the cancel button is clicked | - | +### Methods + +Use [ref](https://v3.vuejs.org/guide/component-template-refs.html) to get Search instance and call instance methods. + +| Name | Description | Attribute | Return value | +| ----- | ------------------- | --------- | ------------ | +| focus | Trigger input focus | - | - | + ### Slots | Name | Description | diff --git a/src/search/README.zh-CN.md b/src/search/README.zh-CN.md index c6cee6b04..63414ddff 100644 --- a/src/search/README.zh-CN.md +++ b/src/search/README.zh-CN.md @@ -157,6 +157,14 @@ export default { | clear | 点击清除按钮后触发 | _event: Event_ | | cancel | 点击取消按钮时触发 | - | +### 方法 + +通过 ref 可以获取到 Search 实例并调用实例方法,详见[组件实例方法](#/zh-CN/advanced-usage#zu-jian-shi-li-fang-fa)。 + +| 方法名 | 说明 | 参数 | 返回值 | +| ------ | -------------- | ---- | ------ | +| focus | 获取输入框焦点 | - | - | + ### Slots | 名称 | 说明 | diff --git a/src/search/index.js b/src/search/index.js index 2631bc937..62d3a667d 100644 --- a/src/search/index.js +++ b/src/search/index.js @@ -1,6 +1,11 @@ +import { ref } from 'vue'; + // Utils import { pick, createNamespace, preventDefault } from '../utils'; +// Composition +import { useExpose } from '../composables/use-expose'; + // Components import Field from '../field'; @@ -34,6 +39,8 @@ export default createComponent({ emits: ['search', 'cancel'], setup(props, { emit, slots, attrs }) { + const filedRef = ref(); + const onCancel = () => { if (!slots.action) { emit('update:modelValue', ''); @@ -75,6 +82,12 @@ export default createComponent({ } }; + const focus = () => { + if (filedRef.value) { + filedRef.value.focus(); + } + }; + const fieldPropNames = [ 'leftIcon', 'rightIcon', @@ -94,6 +107,7 @@ export default createComponent({ return ( (