diff --git a/src/use-query/index.md b/src/use-query/index.md new file mode 100644 index 0000000..77ad4e3 --- /dev/null +++ b/src/use-query/index.md @@ -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` | diff --git a/src/use-query/index.test.ts b/src/use-query/index.test.ts new file mode 100644 index 0000000..74fb563 --- /dev/null +++ b/src/use-query/index.test.ts @@ -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`) + }) +}) diff --git a/src/use-query/index.ts b/src/use-query/index.ts index cfb9e50..20f79ce 100644 --- a/src/use-query/index.ts +++ b/src/use-query/index.ts @@ -2,16 +2,18 @@ * 获取页面 query 参数 * @returns {Partial} */ -const useQuery = >(): Partial => { - const url = location.search - let strObj: any = {} +const useQuery = = {}>( + locationSearch?: string, +): Partial => { + const url = locationSearch || location.search + const strObj: Record = {} 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 } export default useQuery