Skip to content

Commit 8d44538

Browse files
committed
feat: add useRouteParam composable
1 parent a70b9c5 commit 8d44538

2 files changed

Lines changed: 77 additions & 0 deletions

File tree

src/runtime/composables/route.ts

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
import { useRoute } from '#imports'
2+
3+
/**
4+
* A composable that wraps `useRoute` and returns the specified route parameter as a string.
5+
* This avoids repetitive casting (e.g., `route.params.uid as string`) for route parameters.
6+
*
7+
* @param param - The name of the route parameter to retrieve.
8+
* @returns The route parameter value as a string (returns the first element if it is an array, or an empty string if undefined/null).
9+
*/
10+
export const useRouteParam = (param: string): string => {
11+
const route = useRoute()
12+
const value = route.params[param]
13+
14+
if (Array.isArray(value)) {
15+
return value[0] ?? ''
16+
}
17+
18+
return value ?? ''
19+
}

test/route.test.ts

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
import { describe, it, expect, vi, afterEach } from 'vitest'
2+
import { useRouteParam } from '../src/runtime/composables/route'
3+
import { useRoute } from '#imports'
4+
5+
// Mock #imports to isolate useRouteParam testing from a running Nuxt instance
6+
vi.mock('#imports', () => {
7+
return {
8+
useRoute: vi.fn(),
9+
}
10+
})
11+
12+
describe('useRouteParam', () => {
13+
afterEach(() => {
14+
vi.restoreAllMocks()
15+
})
16+
17+
it('returns route param as string when it is a simple string', () => {
18+
vi.mocked(useRoute).mockReturnValue({
19+
params: {
20+
uid: 'user-123',
21+
},
22+
} as unknown as ReturnType<typeof useRoute>)
23+
24+
const param = useRouteParam('uid')
25+
expect(param).toBe('user-123')
26+
})
27+
28+
it('returns first element of array when route param is an array', () => {
29+
vi.mocked(useRoute).mockReturnValue({
30+
params: {
31+
slug: ['category', 'product-name'],
32+
},
33+
} as unknown as ReturnType<typeof useRoute>)
34+
35+
const param = useRouteParam('slug')
36+
expect(param).toBe('category')
37+
})
38+
39+
it('returns empty string if the route param is not present or undefined', () => {
40+
vi.mocked(useRoute).mockReturnValue({
41+
params: {},
42+
} as unknown as ReturnType<typeof useRoute>)
43+
44+
const param = useRouteParam('uid')
45+
expect(param).toBe('')
46+
})
47+
48+
it('returns empty string if the route param is null', () => {
49+
vi.mocked(useRoute).mockReturnValue({
50+
params: {
51+
uid: null as unknown as string,
52+
},
53+
} as unknown as ReturnType<typeof useRoute>)
54+
55+
const param = useRouteParam('uid')
56+
expect(param).toBe('')
57+
})
58+
})

0 commit comments

Comments
 (0)