Skip to content

Commit

Permalink
feat(useCycleList): add go function (#3615)
Browse files Browse the repository at this point in the history
Co-authored-by: Anthony Fu <anthonyfu117@hotmail.com>
  • Loading branch information
loongzhu and antfu committed Feb 20, 2024
1 parent 3fd9434 commit 2ae3639
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 2 deletions.
6 changes: 5 additions & 1 deletion packages/core/useCycleList/index.md
Expand Up @@ -13,7 +13,7 @@ Cycle through a list of items.
```ts
import { useCycleList } from '@vueuse/core'

const { state, next, prev } = useCycleList([
const { state, next, prev, go } = useCycleList([
'Dog',
'Cat',
'Lizard',
Expand All @@ -29,4 +29,8 @@ console.log(state.value) // 'Dog'
prev()

console.log(state.value) // 'Seal'

go(3)

console.log(state.value) // 'Shark'
```
12 changes: 11 additions & 1 deletion packages/core/useCycleList/index.test.ts
Expand Up @@ -33,7 +33,7 @@ describe('useCycleList', () => {
it('should work with ref', () => {
const list = ref(['foo', 'bar', 'fooBar'])

const { state, next, prev, index } = useCycleList(list)
const { state, next, prev, index, go } = useCycleList(list)

expect(state.value).toBe('foo')
expect(index.value).toBe(0)
Expand All @@ -57,6 +57,16 @@ describe('useCycleList', () => {

expect(state.value).toBe('foo')
expect(index.value).toBe(0)

go(1)

expect(state.value).toBe('bar')
expect(index.value).toBe(1)

go(-1)

expect(state.value).toBe('fooBar')
expect(index.value).toBe(2)
})

describe('when list empty', () => {
Expand Down
5 changes: 5 additions & 0 deletions packages/core/useCycleList/index.ts
Expand Up @@ -80,6 +80,7 @@ export function useCycleList<T>(list: MaybeRefOrGetter<T[]>, options?: UseCycleL
index,
next,
prev,
go: set,
}
}

Expand All @@ -88,4 +89,8 @@ export interface UseCycleListReturn<T> {
index: Ref<number>
next: (n?: number) => T
prev: (n?: number) => T
/**
* Go to a specific index
*/
go: (i: number) => T
}

0 comments on commit 2ae3639

Please sign in to comment.