feat(util): add coerceBool function for parsing URL query booleans

添加专门用于处理URL查询参数的布尔值转换函数,解决直接使用Boolean转换字符串'false'、'0'时不符合预期的问题,兼容多种合法的布尔值参数写法。
This commit is contained in:
2026-08-07 16:09:02 +08:00
parent 671c350d95
commit bbef0ecf55

View File

@@ -102,6 +102,36 @@ export function parsePageParams(raw, defaultValue = {}) {
} }
/**
* 把任意值(通常是 URL 参数 / query string 解析出的字符串)强转为布尔值。
*
* 设计动机:URL query 中布尔值的合法写法不止一种——
* ?show_home=1 -> '1' -> true
* ?show_home=true -> 'true' -> true
* ?show_home=true -> true -> true
* ?show_home=0 -> '0' -> false
* ?show_home=false -> 'false' -> false
* ?show_home= -> '' -> false
* 未传 -> undefined -> false
*
* 与裸 `Boolean(x)` 的差异:
* Boolean('false') === true (任何非空字符串都是 true)
* Boolean('0') === true (同上)
* 本函数对这两个值返回 false,更适合 URL 参数解析场景。
*
* @param {*} val 任意值
* @returns {boolean}
*/
export function coerceBool(val) {
if (val === true || val === 1) return true;
if (typeof val === 'string') {
const s = val.trim().toLowerCase();
return s === '1' || s === 'true';
}
return false;
}
// 关于页面路径,使用常量导出 // 关于页面路径,使用常量导出
export const INDEX_PAGE_URL = '/pages/index/index'; export const INDEX_PAGE_URL = '/pages/index/index';
export const CATEGORY_PAGE_URL = '/pages_goods/category'; export const CATEGORY_PAGE_URL = '/pages_goods/category';
@@ -457,6 +487,9 @@ export default {
/** 把 page_params 还原成对象(JSON.parse 的安全封装) */ /** 把 page_params 还原成对象(JSON.parse 的安全封装) */
parsePageParams, parsePageParams,
/** 把任意值强转为布尔值,专治 URL query 参数布尔解析(?show_home=1/'true'/true) */
coerceBool,
/** HTML 实体解码 */ /** HTML 实体解码 */
decodeEntity, decodeEntity,