Skip to content

Commit bd88c7b

Browse files
authored
Merge pull request #55 from qianYuanJ/main
feat: add useQuery
2 parents d0635ea + 0853bc0 commit bd88c7b

File tree

5 files changed

+489
-0
lines changed

5 files changed

+489
-0
lines changed

src/exports.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@ export * from './usePreferredLanguage';
2323
export * from './usePrevPage';
2424
export * from './usePrevRoute';
2525
export * from './useProvider';
26+
export * from './useQuery';
2627
export * from './useRequest';
2728
export * from './useRoute';
2829
export * from './useRouter';

src/index.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@
2525
- [usePrevPage](./usePrevPage/index.md)
2626
- [usePrevRoute](./usePrevRoute/index.md)
2727
- [useProvider](./useProvider/index.md)
28+
- [useQuery](./useQuery/index.md)
2829
- [useRequest](./useRequest/index.md)
2930
- [useRoute](./useRoute/index.md)
3031
- [useRouter](./useRouter/index.md)

src/useQuery/index.md

Lines changed: 267 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,267 @@
1+
# useQuery
2+
3+
获取页面传递的参数,支持自动解析 JSON 字符串。
4+
5+
## 特性
6+
7+
- 🚀 **简单易用** - 一行代码获取页面参数
8+
- 🎯 **智能解析** - 自动识别并解析 JSON 字符串
9+
- 🔧 **灵活配置** - 可选择开启或关闭 JSON 解析
10+
- 📱 **响应式** - 支持响应式参数键
11+
- 🛡️ **类型安全** - 完整的 TypeScript 类型支持
12+
- 🌐 **编码兼容** - 支持 URL 编码的 JSON 数据
13+
14+
## 使用方法
15+
16+
### 基础用法
17+
18+
```vue
19+
<script setup>
20+
import { useQuery } from '@uni-helper/uni-use';
21+
22+
// 获取所有页面参数
23+
const { query } = useQuery();
24+
25+
// 页面跳转: uni.navigateTo({ url: '/pages/detail?id=123&name=test' })
26+
// query.value = { id: '123', name: 'test' }
27+
</script>
28+
```
29+
30+
### 获取特定参数
31+
32+
```vue
33+
<script setup>
34+
import { useQuery } from '@uni-helper/uni-use';
35+
36+
// 获取特定参数的值
37+
const { value: userId } = useQuery('id');
38+
const { value: userName } = useQuery('name');
39+
40+
// 页面跳转: uni.navigateTo({ url: '/pages/detail?id=123&name=test' })
41+
// userId.value = '123'
42+
// userName.value = 'test'
43+
</script>
44+
```
45+
46+
### 自动解析 JSON 数据
47+
48+
```vue
49+
<script setup>
50+
import { useQuery } from '@uni-helper/uni-use';
51+
52+
// 自动解析 JSON 字符串(默认开启)
53+
const { value: resData } = useQuery('resData');
54+
55+
// 页面跳转示例:
56+
// uni.navigateTo({
57+
// url: '/pages/detail?resData=' + encodeURIComponent(JSON.stringify({
58+
// id: 123,
59+
// type: 'coal',
60+
// details: { amount: 50 }
61+
// }))
62+
// })
63+
//
64+
// 结果: resData.value = { id: 123, type: 'coal', details: { amount: 50 } }
65+
</script>
66+
```
67+
68+
### 禁用 JSON 解析
69+
70+
```vue
71+
<script setup>
72+
import { useQuery } from '@uni-helper/uni-use';
73+
74+
// 禁用 JSON 自动解析,所有参数保持为原始字符串
75+
const { query } = useQuery(undefined, { parseJson: false });
76+
77+
// 或者针对特定参数禁用解析
78+
const { value: rawData } = useQuery('data', { parseJson: false });
79+
</script>
80+
```
81+
82+
### 响应式参数键
83+
84+
```vue
85+
<script setup>
86+
import { useQuery } from '@uni-helper/uni-use';
87+
import { ref } from 'vue';
88+
89+
const paramKey = ref('id');
90+
const { value } = useQuery(paramKey);
91+
92+
// 动态改变要获取的参数
93+
paramKey.value = 'name'; // value 会自动更新为对应参数的值
94+
</script>
95+
```
96+
97+
## 支持的 JSON 格式
98+
99+
### encodeURIComponent + JSON.stringify(推荐)
100+
101+
```javascript
102+
// 页面跳转
103+
const data = { id: 123, name: 'test', details: { amount: 50 } };
104+
uni.navigateTo({
105+
url: `/pages/detail?resData=${encodeURIComponent(JSON.stringify(data))}`
106+
});
107+
108+
// 目标页面自动解析
109+
const { value: resData } = useQuery('resData');
110+
// resData.value = { id: 123, name: 'test', details: { amount: 50 } }
111+
```
112+
113+
### 直接 JSON.stringify
114+
115+
```javascript
116+
// 页面跳转
117+
const params = { order: 'A001', type: 'recruitment' };
118+
uni.navigateTo({
119+
url: `/pages/order?data=${JSON.stringify(params)}`
120+
});
121+
122+
// 目标页面自动解析
123+
const { value: orderData } = useQuery('data');
124+
// orderData.value = { order: 'A001', type: 'recruitment' }
125+
```
126+
127+
## API 参考
128+
129+
### useQuery()
130+
131+
```typescript
132+
function useQuery(): {
133+
query: Ref<Record<string, any>>;
134+
};
135+
```
136+
137+
获取所有页面参数。
138+
139+
### useQuery(key, options?)
140+
141+
```typescript
142+
function useQuery(
143+
key: MaybeRefOrGetter<string>,
144+
options?: UseQueryOptions
145+
): {
146+
value: Ref<any>;
147+
};
148+
```
149+
150+
#### 参数
151+
152+
- **key**: `MaybeRefOrGetter<string>` - 要获取的参数键名,支持响应式
153+
- **options**: `UseQueryOptions` - 配置选项
154+
155+
#### UseQueryOptions
156+
157+
```typescript
158+
interface UseQueryOptions {
159+
/**
160+
* 是否自动解析 JSON 字符串
161+
* @default true
162+
*/
163+
parseJson?: boolean;
164+
}
165+
```
166+
167+
#### 返回值
168+
169+
- **query**: `Ref<Record<string, any>>` - 所有页面参数(仅在不传 key 时返回)
170+
- **value**: `Ref<any>` - 指定参数的值(仅在传入 key 时返回)
171+
172+
## 辅助函数
173+
174+
### tryParseJson
175+
176+
```typescript
177+
function tryParseJson(value: string): any;
178+
```
179+
180+
尝试解析 JSON 字符串,支持自动处理 URL 编码。
181+
182+
**特性:**
183+
- 智能检测 JSON 格式
184+
- 自动处理 URL 编码(encodeURIComponent)
185+
- 解析失败时返回原始字符串
186+
- 处理各种边界情况
187+
188+
**示例:**
189+
190+
```javascript
191+
import { tryParseJson } from '@uni-helper/uni-use';
192+
193+
// 普通 JSON
194+
tryParseJson('{"id":123}'); // { id: 123 }
195+
196+
// URL 编码的 JSON
197+
tryParseJson('%7B%22id%22%3A123%7D'); // { id: 123 }
198+
199+
// 非 JSON 字符串
200+
tryParseJson('hello'); // 'hello'
201+
202+
// 无效 JSON
203+
tryParseJson('{"invalid":}'); // '{"invalid":}'
204+
```
205+
206+
## API
207+
208+
## 实际使用场景
209+
210+
### 场景一:商品详情页
211+
212+
```javascript
213+
// 商品列表页跳转
214+
const product = { id: 'P001', name: '商品A', price: 99.99 };
215+
uni.navigateTo({
216+
url: `/pages/product/detail?product=${encodeURIComponent(JSON.stringify(product))}`
217+
});
218+
219+
// 商品详情页接收
220+
const { value: productInfo } = useQuery('product');
221+
// productInfo.value = { id: 'P001', name: '商品A', price: 99.99 }
222+
```
223+
224+
### 场景二:订单页面
225+
226+
```javascript
227+
// 订单创建页跳转
228+
const orderData = {
229+
items: [{ id: 1, qty: 2 }],
230+
total: 198,
231+
userId: 'U001'
232+
};
233+
uni.navigateTo({
234+
url: `/pages/order/create?data=${JSON.stringify(orderData)}`
235+
});
236+
237+
// 订单创建页接收
238+
const { value: order } = useQuery('data');
239+
// order.value = { items: [{ id: 1, qty: 2 }], total: 198, userId: 'U001' }
240+
```
241+
242+
### 场景三:混合参数
243+
244+
```javascript
245+
// 复杂页面跳转
246+
const complexData = { config: { theme: 'dark' }, user: { role: 'admin' } };
247+
uni.navigateTo({
248+
url: `/pages/dashboard?id=123&source=menu&config=${encodeURIComponent(JSON.stringify(complexData))}`
249+
});
250+
251+
// 目标页面接收
252+
const { query } = useQuery();
253+
// query.value = {
254+
// id: '123',
255+
// source: 'menu',
256+
// config: { config: { theme: 'dark' }, user: { role: 'admin' } }
257+
// }
258+
```
259+
260+
## 注意事项
261+
262+
1. **JSON 解析优先级**:先尝试直接解析,失败后尝试 URL 解码再解析
263+
2. **类型安全**:建议配合 TypeScript 使用以获得更好的类型提示
264+
3. **性能考虑**:JSON 解析在 `onLoad` 生命周期中执行,不会影响页面性能
265+
4. **错误处理**:解析失败时会保持原始字符串值,不会抛出错误
266+
5. **响应式更新**:参数值在页面生命周期内保持响应式
267+
6. **编码建议**:推荐使用 `encodeURIComponent` 来确保特殊字符的正确传输

0 commit comments

Comments
 (0)