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(useQuery): 增加测试用例 & docs #2

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 42 additions & 0 deletions src/use-query/index.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
---
title: useQuery
nav:
title: Hooks
path: /hooks
group:
title: Data
path: /data
---

# useQuery

获取页面 query 参数

## 代码演示

### 基础用法

## API

```typescript
// location.search = https://ai-indeed.com?id=11
const { id } = useQuery<{ id: string }>()
console.log(id) // 11
```

```typescript
// location.search = https://ai-indeed.com
const { id } = useQuery<{ id: string }>()
console.log(id) // undefined
```

```typescript
const { id } = useQuery<{ id: string }>(`https://ai-indeed.com?id=12`)
console.log(id) // 12
```

### 参数

| 参数 | 说明 | 类型 | 默认值 | 返回值 |
| ---- | ---------- | ------ | ----------------- | ------ |
| url | 地址栏 url | string | `location.search` | `{}` | `Partial<T>` |
15 changes: 15 additions & 0 deletions src/use-query/index.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import useQuery from './index'

describe('useQuery', () => {
it('test useQuery return params', () => {
const result = useQuery<{ a: string }>(`https://aiindeed.com?a=1`)
expect(result.a).toEqual(`1`)
})
it('test useQuery return params 2', () => {
const result = useQuery<{ a: string; b: string }>(
`https://aiindeed.com?a=1&b=2`,
)
expect(result.a).toEqual(`1`)
expect(result.b).toEqual(`2`)
})
})
12 changes: 7 additions & 5 deletions src/use-query/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,16 +2,18 @@
* 获取页面 query 参数
* @returns {Partial<T>}
*/
const useQuery = <T extends Record<string, string>>(): Partial<T> => {
const url = location.search
let strObj: any = {}
const useQuery = <T extends Record<string, string> = {}>(
locationSearch?: string,
): Partial<T> => {
const url = locationSearch || location.search
const strObj: Record<string, string> = {}
if (url.includes('?')) {
const strs = url.slice(url.indexOf('?') + 1).split('&')
strs.forEach(str => {
strObj[str.split('=')[0]] = str.split('=')[1]
strObj[str.split('=')[0]] = str.split('=')?.[1]
})
}
return strObj
return strObj as Partial<T>
}

export default useQuery