Files
uniapp-im-shop/utils/router.js
2025-12-24 02:01:34 +08:00

73 lines
1.8 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.
// 统一页面跳转工具函数
/**
* 辅助函数:拼接 URL 参数
* @param {string} url - 页面路径,如 '/pages/home/home'
* @param {object} params - 参数对象,如 { id: 123, name: 'test' }
* @returns {string} 拼接后的完整 url
*/
const appendParams = (url, params) => {
if (!params || Object.keys(params).length === 0) {
return url
}
const query = Object.entries(params)
.map(([key, value]) => {
// 处理复杂类型(如对象、数组)需序列化
if (typeof value === 'object') {
value = encodeURIComponent(JSON.stringify(value))
} else {
value = encodeURIComponent(String(value))
}
return `${key}=${value}`
})
.join('&')
return url.includes('?') ? `${url}&${query}` : `${url}?${query}`
}
/**
* 普通跳转(保留返回)
*/
export const navigateTo = (url, params = {}) => {
const finalUrl = appendParams(url, params)
return uni.navigateTo({
url: finalUrl
})
}
/**
* 关闭当前页,跳转到应用内某个页面(不可返回)
*/
export const redirectTo = (url, params = {}) => {
const finalUrl = appendParams(url, params)
return uni.redirectTo({ url: finalUrl })
}
/**
* 关闭所有页面,打开到应用内某个页面
*/
export const reLaunch = (url, params = {}) => {
const finalUrl = appendParams(url, params)
return uni.reLaunch({ url: finalUrl })
}
/**
* 返回上一页(可指定 delta
*/
export const navigateBack = (delta = 1) => {
return uni.navigateBack({ delta })
}
/**
* 跳转到 tabBar 页面(只能用 switchTab
*/
export const switchTab = (url, params = {}) => {
if (Object.keys(params).length > 0) {
console.warn(
'switchTab 不支持携带参数,请使用全局状态或 storage 传递'
)
}
return uni.switchTab({ url })
}