Skip to content

Commit

Permalink
feat: useUrlState add detectNumber option
Browse files Browse the repository at this point in the history
  • Loading branch information
zuofenghua committed Dec 9, 2021
1 parent 93013b9 commit a77ef4f
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 6 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "ahooks-vue",
"version": "0.12.2",
"version": "0.12.3",
"description": "ahooks-vue",
"types": "dist/src/index.d.ts",
"repository": "https://github.com/dewfall123/ahooks-vue.git",
Expand Down
11 changes: 6 additions & 5 deletions src/useUrlState/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { useLocalStorageState } from '../useLocalStorageState';

export interface UseUrlStateOptions {
localStorageKey?: string;
detectNumber?: boolean;
}

interface UrlState {
Expand All @@ -14,7 +15,7 @@ function encodeParams(value: UrlState) {
return qs.stringify(value);
}

function decodeParams(valueStr: string) {
function decodeParams(valueStr: string, detectNumber: boolean) {
// return JSON.parse(decodeURIComponent(atob(valueStr)));
return qs.parse(valueStr, {
// fix: 数组长度限制问题
Expand All @@ -26,7 +27,7 @@ function decodeParams(valueStr: string) {
return strWithoutPlus.replace(/%[0-9a-f]{2}/gi, unescape);
}

if (/^[+-]?\d+(\.\d+)?$/.test(str)) {
if (detectNumber && /^[+-]?\d+(\.\d+)?$/.test(str)) {
return parseFloat(str);
}

Expand Down Expand Up @@ -55,7 +56,7 @@ export function useUrlState<S extends UrlState = UrlState>(
initialState?: S | (() => S),
options?: UseUrlStateOptions,
): Ref<S> {
const { localStorageKey } = options ?? {};
const { localStorageKey, detectNumber = true } = options ?? {};

const [path, paramsStr] = location.hash.slice(1).split('?');

Expand All @@ -72,7 +73,7 @@ export function useUrlState<S extends UrlState = UrlState>(
// 初始状态 url > localstorage
if (paramsStr) {
try {
const paramsValue = decodeParams(paramsStr);
const paramsValue = decodeParams(paramsStr, detectNumber);
console.log('解析url结果:');
console.log(paramsValue);
state.value = {
Expand All @@ -87,7 +88,7 @@ export function useUrlState<S extends UrlState = UrlState>(

// 去掉多余的key
if (initialState && Object.keys(initialState).length) {
let newState = { ...initialState } as any;
const newState = { ...initialState } as any;
for (const key in newState) {
if (key in state.value) {
newState[key] = state.value[key];
Expand Down

0 comments on commit a77ef4f

Please sign in to comment.