Skip to content

Commit

Permalink
feat(useRouteParams): new function (#1173)
Browse files Browse the repository at this point in the history
Co-authored-by: Anthony Fu <anthonyfu117@hotmail.com>
  • Loading branch information
DevilTea and antfu committed Jul 6, 2022
1 parent 44526f0 commit ece3dff
Show file tree
Hide file tree
Showing 3 changed files with 53 additions and 0 deletions.
1 change: 1 addition & 0 deletions packages/router/index.ts
@@ -1,2 +1,3 @@
export * from './useRouteHash'
export * from './useRouteQuery'
export * from './useRouteParams'
20 changes: 20 additions & 0 deletions packages/router/useRouteParams/index.md
@@ -0,0 +1,20 @@
---
category: '@Router'
---

# useRouteParams

Shorthand for reactive route.params

## Usage

```ts
import { useRouteParams } from '@vueuse/router'

const userId = useRouteParams('userId')

const userId = useRouteParams('userId', '-1') // or with a default value

console.log(userId.value) // route.params.userId
userId.value = '100' // router.replace({ params: { userId: '100' } })
```
32 changes: 32 additions & 0 deletions packages/router/useRouteParams/index.ts
@@ -0,0 +1,32 @@
import type { Ref } from 'vue-demi'
import { computed, nextTick, unref } from 'vue-demi'
import { useRoute, useRouter } from 'vue-router'
import type { ReactiveRouteOptions } from '../_types'

export function useRouteParams(name: string): Ref<null | string | string[]>
export function useRouteParams<T extends null | undefined | string | string[] = null | string | string[]>(name: string, defaultValue?: T, options?: ReactiveRouteOptions): Ref<T>
export function useRouteParams<T extends string | string[]>(
name: string,
defaultValue?: T,
{
mode = 'replace',
route = useRoute(),
router = useRouter(),
}: ReactiveRouteOptions = {},
) {
return computed<any>({
get() {
const data = route.params[name]
if (data == null)
return defaultValue ?? null
if (Array.isArray(data))
return data.filter(Boolean)
return data
},
set(v) {
nextTick(() => {
router[unref(mode)]({ params: { ...route.params, [name]: v } })
})
},
})
}

0 comments on commit ece3dff

Please sign in to comment.