diff --git a/src/index-bar/README.md b/src/index-bar/README.md index be408f58a..b26a5f932 100644 --- a/src/index-bar/README.md +++ b/src/index-bar/README.md @@ -90,6 +90,14 @@ export default { | ------- | ------------------------------------- | | default | Anchor content, show index by default | +### Methods + +Use [ref](https://v3.vuejs.org/guide/component-template-refs.html) to get IndexBar instance and call instance methods. + +| Name | Description | Attribute | Return value | +| --- | --- | --- | --- | +| scrollTo | scroll to target element | _index: number \| string_ | - | + ### Less Variables How to use: [Custom Theme](#/en-US/theme). diff --git a/src/index-bar/README.zh-CN.md b/src/index-bar/README.zh-CN.md index 8466e3f43..d1d268ad3 100644 --- a/src/index-bar/README.zh-CN.md +++ b/src/index-bar/README.zh-CN.md @@ -88,6 +88,14 @@ export default { | select | 点击索引栏的字符时触发 | _index: number \| string_ | | change `v2.10.10` | 当前高亮的索引字符变化时触发 | _index: number \| string_ | +### 方法 + +通过 ref 可以获取到 IndexBar 实例并调用实例方法,详见[组件实例方法](#/zh-CN/advanced-usage#zu-jian-shi-li-fang-fa)。 + +| 方法名 | 说明 | 参数 | 返回值 | +| -------- | -------------- | ------------------------- | ------ | +| scrollTo | 滚动到指定锚点 | _index: number \| string_ | - | + ### IndexAnchor Slots | 名称 | 说明 | diff --git a/src/index-bar/index.js b/src/index-bar/index.js index 2d78b7c11..8358c6e4c 100644 --- a/src/index-bar/index.js +++ b/src/index-bar/index.js @@ -19,6 +19,7 @@ import { useEventListener, } from '@vant/use'; import { useTouch } from '../composables/use-touch'; +import { useExpose } from '../composables/use-expose'; export const INDEX_BAR_KEY = 'vanIndexBar'; @@ -179,8 +180,7 @@ export default createComponent({ ); }); - const scrollToElement = (element) => { - const { index } = element.dataset; + const scrollTo = (index) => { if (!index) { return; } @@ -198,6 +198,11 @@ export default createComponent({ } }; + const scrollToElement = (element) => { + const { index } = element.dataset; + scrollTo(index); + }; + const onClick = (event) => { scrollToElement(event.target); }; @@ -223,6 +228,8 @@ export default createComponent({ } }; + useExpose({ scrollTo }); + return () => (
{ Element.prototype.getBoundingClientRect = nativeRect; }); + +test('scroll to target element', () => { + const onSelect = jest.fn(); + mount({ + template: ` + + + + + + + + + + `, + methods: { + onSelect, + }, + mounted() { + this.$refs.anchorRef.scrollTo('C'); + }, + }); + + const fn = mockScrollIntoView(); + + expect(fn).toHaveBeenCalledTimes(1); + expect(onSelect).toHaveBeenCalledWith('C'); +});