Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(useRouteParams): new function #1173

Merged
merged 2 commits into from Jul 6, 2022
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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 } })
})
},
})
}