2025-10-10 11:24:23 +08:00

104 lines
3.1 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// utils/navigator.js
export default {
/**
* 导航到指定页面
* @param {string} url - 页面路径
* @param {object} params - 传递的参数
* @param {object} options - 导航选项
* @param {boolean} options.relaunch - 是否使用relaunch方式导航
* @param {boolean} options.redirect - 是否使用redirect方式导航
* @param {boolean} options.switchTab - 是否使用switchTab方式导航
* @returns {Promise} - 导航成功/失败的Promise
*/
to(url, params = {}, options = {}) {
// 处理参数
const queryString = this._serializeParams(params);
const fullUrl = queryString ? `${url}?${queryString}` : url;
// 根据不同的导航方式调用对应的API
if (options.relaunch) {
return this._navigate(uni.reLaunch, fullUrl);
} else if (options.redirect) {
return this._navigate(uni.redirectTo, fullUrl);
} else if (options.switchTab) {
return this._navigate(uni.switchTab, fullUrl);
} else {
return this._navigate(uni.navigateTo, fullUrl);
}
},
/**
* 返回上一页
* @param {number} delta - 返回的页面数
* @returns {Promise} - 导航成功/失败的Promise
*/
back(delta = 1) {
return new Promise((resolve, reject) => {
uni.navigateBack({
delta,
success: resolve,
fail: reject
});
});
},
/**
* 序列化参数对象为查询字符串
* @param {object} params - 参数对象
* @returns {string} - 序列化后的查询字符串
*/
_serializeParams(params) {
return Object.keys(params)
.filter(key => params[key] !== undefined && params[key] !== null)
.map(key => {
const value = params[key];
// 特殊处理对象类型的参数先JSON.stringify再encodeURIComponent
const encodedValue = typeof value === 'object'
? encodeURIComponent(JSON.stringify(value))
: encodeURIComponent(value);
return `${key}=${encodedValue}`;
})
.join('&');
},
/**
* 统一的导航方法处理Promise包装和错误捕获
* @param {Function} navApi - uni-app的导航API
* @param {string} url - 导航URL
* @returns {Promise} - 导航成功/失败的Promise
*/
_navigate(navApi, url) {
return new Promise((resolve, reject) => {
navApi({
url,
success: (res) => {
// console.log(`导航成功: ${url}`, res);
resolve(res);
},
fail: (err) => {
console.error(`导航失败: ${url}`, err);
reject(err);
}
});
});
},
/**
* 获取页面参数(处理复杂参数的反序列化)
* @param {object} options - 页面的onLoad options参数
* @returns {object} - 解析后的参数对象
*/
getParams(options) {
const params = { ...options };
Object.keys(params).forEach(key => {
try {
// 尝试解析JSON格式的参数
params[key] = JSON.parse(decodeURIComponent(params[key]));
} catch (e) {
// 如果解析失败,使用原始值
params[key] = decodeURIComponent(params[key]);
}
});
return params;
}
};