cashier_app/commons/utils/go.js

109 lines
2.7 KiB
JavaScript
Raw 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.

/**
* 页面跳转工具类
*
* @author terrfly
* @site https://www.jeequan.com
* @date 2022/11/14 17:12
*/
// 引入 pages用于解析 pageId 变量 , 注意 需要在 pages.json 定义pageId 参数。
// 使用方法: go.to(""), 优点: 扩展分包可任意路径业务调用不再传入固定URL, 传入的是pageId变量。
import pagesJSON from '@/pages.json'
import emit from './emit.js'
// 获取到全部的页面路径 和 ID
const ALL_PAGES = { }
// 添加到 ALL_PAGES
function addPages(pagesRoot){
let rootUrl = pagesRoot.root ? `/${pagesRoot.root}/` : '/'
pagesRoot.pages.forEach(r => {
if(r.pageId){
ALL_PAGES[r.pageId] = rootUrl + r.path
}
})
}
// 1. 添加 主目录
addPages(pagesJSON)
// 2. 添加分包文件 目录
if(pagesJSON.subPackages){
pagesJSON.subPackages.forEach(r => addPages(r))
}
const model = {
// 跳转类型
GO_TYPE_TO: 'navigateTo',
GO_TYPE_REDIRECT: 'redirect',
GO_TYPE_RELAUNCH: 'reLaunch',
GO_TYPE_SWITCHTAB: 'switchTab',
// 对象转换url参数
object2param: (obj) => {
if(!obj || Object.keys(obj).length <= 0){
return ""
}
let result = "?"
Object.keys(obj).forEach(k => {
let val = obj[k]
// H5需要转码 其他平台不需要
// #ifdef H5
val = encodeURIComponent(val)
// #endif
result += `${k}=${val}&`
})
return result.substr(0, (result.length - 1));
},
// uni.navigateTo函数的封装 保留当前页面跳转到应用内的某个页面使用uni.navigateBack可以返回到原页面。
// 参数: pagesIdOrUrl(路径或者pageId), 页面参数, 扩展参数
to: (pagesIdOrUrl, params = {}, type = model.GO_TYPE_TO, extObject = {}) => {
// 使用ID作为标识
if(pagesIdOrUrl.indexOf('PAGES_') == 0){
pagesIdOrUrl = ALL_PAGES[pagesIdOrUrl]
}
pagesIdOrUrl += model.object2param(params)
if(type == model.GO_TYPE_TO){
uni.navigateTo(Object.assign({ url: pagesIdOrUrl }, extObject))
}
if(type == model.GO_TYPE_REDIRECT){
uni.redirectTo(Object.assign({ url: pagesIdOrUrl }, extObject))
}
if(type == model.GO_TYPE_RELAUNCH){
uni.reLaunch(Object.assign({ url: pagesIdOrUrl }, extObject))
}
if(type == model.GO_TYPE_SWITCHTAB){
uni.switchTab(Object.assign({ url: pagesIdOrUrl }, extObject))
}
},
// 跳转到通用搜索页面
toSearchPage: (pageType, extObject = {}) => {
model.to("PAGES_LIST_SEARCH", Object.assign({type: pageType}, extObject))
},
// delta 返回到第几页, refEmitEventName: 触发全局更新函数 (更新 list and search )
back: (delta = 1, refEmitEventName) => {
if(refEmitEventName){
emit.refPageAndSearchEmit(refEmitEventName)
}
uni.navigateBack(delta)
}
}
export default model