Commit 526d78e1 by liimin

refactor(router): 重构路由系统并优化登录状态检查

- 重构 Router 类,增加权限检查和路由拦截功能
- 优化登录状态检查逻辑,使用 wx.p.isLogin 替代 wx.$LoginStatus
- 调整路由跳转方法,支持传参和特殊页面处理
- 移除全局事件注册,降低潜在风险
1 parent b80d34f1
......@@ -3,7 +3,7 @@
import sentryInit from "~/utils/sentryConfig/sentryInit";
sentryInit();
import api from "./api/index";
import { router } from "./router/index";
import { router, routerBefore } from "./router/index";
// 判断小程序是否需要更新
import { getUpdateManager } from "./lib/index";
import utils from "./utils/index";
......@@ -20,6 +20,7 @@ App({
...utils,
api,
router,
isLogin:false,
storage: new utils.cache.Storage(),
};
// 存储设备信息
......@@ -40,4 +41,4 @@ App({
goodsLoaded: false,
goodsCommodityList: []
},
});
});
\ No newline at end of file
export const ToolList = Object.freeze([
{
text: '我的地址',
icon: 'myAddress',
url: '/packageMine/pages/address/index/index'
}
text: "我的地址",
icon: "myAddress",
url: "/packageMine/pages/address/index/index",
},
]);
export const ORDER_LIST = Object.freeze([
{
text: "待付款",
image: "noPay",
code: 1,
},
{
text: "待发货",
image: "noTakeCommodity",
code: 3,
},
{
text: "待收货",
image: "takeCommodity",
code: 2,
},
{
text: "退款/售后",
image: "aftermarket",
code: 5,
},
]);
\ No newline at end of file
......@@ -173,7 +173,7 @@ Page({
this.toOpenPage()
},
async toRecharge() {
const loginStatus = await wx.p.router.intercept()
const loginStatus = !wx.p.isLogin
if (loginStatus) return
if (!this.data.rechageNum) {
wx.p.wxApi.showToast('请输入充值账号')
......
......@@ -217,7 +217,7 @@ Page({
},
// 去购买
async toBuyItem() {
const loginStatus = await wx.p.router.intercept()
const loginStatus = !wx.p.isLogin
if (loginStatus) return
const {
curentGoodsItem,
......
......@@ -70,7 +70,7 @@ Page({
Object.assign(para, this.staff)
}
// 先判断登录
const loginStatus = await wx.p.router.intercept()
const loginStatus = !wx.p.isLogin
if (loginStatus) return
wx.p.wxApi.showLoading('领取中')
wx.p.api.couponsApi.giftsRecive(para).then(res => {
......
......@@ -51,7 +51,7 @@ Page({
},
async tofreeReceive() {
// 先判断登录
const loginStatus = await wx.p.router.intercept()
const loginStatus = !wx.p.isLogin
if (loginStatus) return
const userInfo = wx.p.storage.get('userInfo')
......
......@@ -53,7 +53,7 @@ Page({
},
// 去购买会员
async openMemberFn() {
const loginStatus = await wx.p.router.intercept()
const loginStatus = !wx.p.isLogin
const { merchantId } = wx.p.storage.get('merchant_info')
if (loginStatus) return
const {
......
......@@ -44,7 +44,7 @@ Page({
this.setData({
showAuthBtn: false
})
const loginStatus = await wx.p.router.intercept(false)
const loginStatus = !wx.p.isLogin
if (loginStatus) return this.setData({
showAuthBtn: true
})
......@@ -117,7 +117,7 @@ Page({
},
// 获取门店单号
async toCreatePackageNum() {
const loginStatus = await wx.p.router.intercept()
const loginStatus = !wx.p.isLogin
if (loginStatus) return
wx.p.wxApi.showLoading()
wx.p.api.couponsApi.createOrderNum().then(res => {
......
......@@ -50,7 +50,7 @@ Page({
// )
},
async getServiceCode() {
const loginStatus = await wx.p.router.intercept()
const loginStatus = !wx.p.isLogin
if (loginStatus) return
wx.p.wxApi.showLoading('加载中...')
let {
......
......@@ -49,7 +49,7 @@ Page({
// )
},
async getServiceCode() {
const loginStatus = await wx.p.router.intercept()
const loginStatus = !wx.p.isLogin
if (loginStatus) return
wx.p.wxApi.showLoading('加载中...')
let {
......
......@@ -226,62 +226,62 @@ Page({
shareSource
} = this.data
if (!couponId && !userCouponId) return
wx.p.router.intercept().then(response => {
if (response) {
this.setData({
isReceive: true
})
return
}
let obj = {
...this.data.shareStaff
}
if (userCouponId) obj.userCouponId = userCouponId
if (couponId) obj.couponId = couponId
if (issueName) obj.issueName = issueName
if (issueDate) obj.issueDate = issueDate
if (merchantId) obj.merchantId = merchantId
if (shareSource) obj.shareSource = shareSource
this.checkCoupon(obj, () => {
wx.p.api.couponsApi.receiveCoupon(obj).then(({
code,
data,
message
}) => {
if (code == '0') {
// wx.$Track.setTrack({
// data,
// type: '领取优惠券'
// },
// 7
// )
console.log(data)
if (data.discountType == 3) {
this.jump()
return
}
this.setData({
qr: QR.createQrCodeImg(`t=2&c=${data.verificationCode}`),
verificationCode: data.verificationCode
})
wx.p.wxApi.showToast('领取成功')
this.checkCoupon(obj)
if (this.data.activiOptions) {
// wx.$util.reportData(this.data.activiOptions, false, true)
}
if (this.data.recommandOptions) {
let options = this.data.recommandOptions
options.item_type = 2
options.action_type = 2
options.item_id = options.couponId
// wx.$util.reportData(options, false, false, true)
}
} else {
wx.p.wxApi.showToast(message)
}
})
})
})
// wx.p.router.intercept().then(response => {
// if (response) {
// this.setData({
// isReceive: true
// })
// return
// }
// let obj = {
// ...this.data.shareStaff
// }
// if (userCouponId) obj.userCouponId = userCouponId
// if (couponId) obj.couponId = couponId
// if (issueName) obj.issueName = issueName
// if (issueDate) obj.issueDate = issueDate
// if (merchantId) obj.merchantId = merchantId
// if (shareSource) obj.shareSource = shareSource
// this.checkCoupon(obj, () => {
// wx.p.api.couponsApi.receiveCoupon(obj).then(({
// code,
// data,
// message
// }) => {
// if (code == '0') {
// // wx.$Track.setTrack({
// // data,
// // type: '领取优惠券'
// // },
// // 7
// // )
// console.log(data)
// if (data.discountType == 3) {
// this.jump()
// return
// }
// this.setData({
// qr: QR.createQrCodeImg(`t=2&c=${data.verificationCode}`),
// verificationCode: data.verificationCode
// })
// wx.p.wxApi.showToast('领取成功')
// this.checkCoupon(obj)
// if (this.data.activiOptions) {
// // wx.$util.reportData(this.data.activiOptions, false, true)
// }
// if (this.data.recommandOptions) {
// let options = this.data.recommandOptions
// options.item_type = 2
// options.action_type = 2
// options.item_id = options.couponId
// // wx.$util.reportData(options, false, false, true)
// }
// } else {
// wx.p.wxApi.showToast(message)
// }
// })
// })
// })
},
/**
* 生命周期函数--监听页面初次渲染完成
......
......@@ -144,7 +144,7 @@ Page({
else this.join()
},
async pay(e) {
const loginStatus = await wx.p.router.intercept()
const loginStatus = !wx.p.isLogin
if (loginStatus) return
let {
isActivity,
......@@ -224,7 +224,7 @@ Page({
})
},
async join(e) {
const loginStatus = await wx.p.router.intercept()
const loginStatus = !wx.p.isLogin
if (loginStatus) return
let params = e && e.detail
if (!params) {
......@@ -395,7 +395,7 @@ Page({
})
},
async getGoodscouponList(id) {
const res = await wx.p.router.intercept(false),
const res = !wx.p.isLogin,
{
merchantId
} = wx.p.storage.get('merchant_info')
......@@ -441,7 +441,7 @@ Page({
})
},
async getUserAddressList() {
const res = await wx.p.router.intercept(false)
const res = !wx.p.isLogin
if (res) return
wx.p.api.mineApi.getUserAddressList().then(data => {
if (!data.length) {
......@@ -458,7 +458,7 @@ Page({
})
},
async getUserAddressDefault() {
const res = await wx.p.router.intercept(false)
const res = !wx.p.isLogin
if (res) this.setData({
addressFlag: true
})
......
......@@ -97,7 +97,7 @@ Page({
})
},
async onLoad(options) {
const showLogin = await wx.p.router.intercept(false)
const showLogin =!wx.p.isLogin
this.setData({
showLogin
})
......
......@@ -3,6 +3,7 @@ import {
orderMixin
} from '~/mixins/index'
import NP from 'number-precision'
import { ORDER_LIST } from "~/constants/mine.js";
/**查询订单
* '全部 ', '待付款 1', '待发货 3', '待收货 2', '评价 4', '退款/售后 5'
*/
......@@ -12,6 +13,7 @@ const orderStatusPartEnum = {
2: 3,
3: 2,
4: 5,
5: 6,
}
Page({
behaviors: [orderMixin],
......@@ -20,7 +22,7 @@ Page({
*/
data: {
pageNum: 1,
tab: ['全部', '待付款', '待发货', '待收货', '退款/售后'],
tab: ['全部', '待付款', '待发货', '待收货', '已完成', '退款/售后'],
list: [],
hasUserInfo: true,
},
......@@ -157,11 +159,13 @@ Page({
* 生命周期函数--监听页面加载
*/
onLoad: function (options) {
this.setData({
tabIndex: options.tabIndex,
orderStatusPart: orderStatusPartEnum[options.tabIndex],
wx.p.router.getRouterParams(options).then(option=>{
this.setData({
tabIndex: option.code,
orderStatusPart: orderStatusPartEnum[option.code],
})
this.clearData()
})
this.clearData()
},
onShow() {
if (this.refresh) this.clearData()
......@@ -170,7 +174,7 @@ Page({
this.refresh = true
},
async clearData() {
const res = await wx.p.router.intercept()
const res = !wx.p.isLogin
if (res) return
this.setData({
listFlag: false,
......
......@@ -12,7 +12,7 @@ Page({
wx.p.wxApi.showLoading()
if (code == '0') {
// wx.$Track.setTrack({}, 4)
wx.$LoginStatus = true
wx.p.isLogin = false
// wx.$util.removeSystemStorage()
wx.p.storage.rm('userInfo')
wx.p.storage.rm('sessionId')
......
......@@ -161,7 +161,7 @@ Page({
},
/**C端登录回调 */
customerLoginCallBack(data) {
wx.$LoginStatus = false
wx.p.isLogin = true
wx.p.storage.set('userInfo', data)
wx.p.storage.set('sessionId', data.sessionId)
// 返回上一页
......
// pages/loading/loading.js
import {
systemApi
} from '~/api/index'
import { systemApi } from "~/api/index";
Page({
/**
* 页面的初始数据
*/
data: {
},
data: {},
/**
* 生命周期函数--监听页面加载
*/
async onLoad(options) {
console.log('---------------- 页面初始化 ----------------')
console.log('options参数:', options)
systemApi.getImageVersion() //获取图片版本号
this.tabList = __wxConfig.tabBar.list
wx.p.wxApi.showLoading()
console.log("---------------- 页面初始化 ----------------");
console.log("options参数:", options);
systemApi.getImageVersion(); //获取图片版本号
this.tabList = __wxConfig.tabBar.list;
wx.p.wxApi.showLoading();
//scenc获取页面参数并跳转
if (options.scene) {
return this.getSceneById(options.scene)
return this.getSceneById(options.scene);
}
if (options.url) {
return this.login(options)
return this.login(options);
}
this.login()
this.login();
},
async login(options = {}) {
if (options.merchantId) wx.$merchant_id = options.merchantId
if (options.merchantId) wx.$merchant_id = options.merchantId;
try {
const {
code,
data,
message
} = await wx.p.api.userApi.login()
wx.$LoginStatus = code != 0
if (data) wx.p.storage.set('merchant_info', {
merchantId: data.merchantId,
merchantName: data.merchantName
})
if (code == '0') {
wx.p.storage.set('userInfo', data)
wx.p.storage.set('sessionId', data.sessionId)
if (!data) throw message
const { code, data, message } = await wx.p.api.userApi.login();
if (data)
wx.p.storage.set("merchant_info", {
merchantId: data.merchantId,
merchantName: data.merchantName,
});
if (code == "0") {
wx.p.isLogin = true;
wx.p.storage.set("userInfo", data);
wx.p.storage.set("sessionId", data.sessionId);
if (!data) throw message;
} else {
wx.p.storage.rm('userInfo')
wx.p.storage.rm('sessionId')
wx.p.isLogin = false;
wx.p.storage.rm("userInfo");
wx.p.storage.rm("sessionId");
}
console.log('登陆信息:', data)
console.log("登陆信息:", data);
if (options.url) {
return this.jumpPage(options.url)
return this.jumpPage(options.url);
}
// 默认跳转到首页
wx.p.router.goHome()
wx.p.router.goHome();
} catch (error) {
wx.$LoginStatus = true //请求失败默认未登录
console.log(error)
wx.p.wxApi.showToast(String(error))
wx.p.router.goHome()
wx.p.isLogin = false; //请求失败默认未登录
console.log(error);
wx.p.wxApi.showToast(String(error));
wx.p.router.goHome();
}
},
async getSceneById(scene) {
const id = decodeURIComponent(scene).split('=').at(-1)
const id = decodeURIComponent(scene).split("=").at(-1);
try {
const {
code,
data
} = await wx.p.api.wechatApi.getSceneById({
id
})
const params = data.scene.split('url='),
options = {}
if (params.length > 1) options.url = params.at(-1)
if (code == 0) this.login(options)
else throw {}
const { code, data } = await wx.p.api.wechatApi.getSceneById({
id,
});
const params = data.scene.split("url="),
options = {};
if (params.length > 1) options.url = params.at(-1);
if (code == 0) this.login(options);
else throw {};
} catch (error) {
wx.p.wxApi.showToast(error || '获取scene失败')
this.login()
wx.p.wxApi.showToast(error || "获取scene失败");
this.login();
}
},
jumpPage(val) {
const targetPath = decodeURIComponent(val),
{
url,
events
} = this.setRouteData(targetPath),
routeName = this.tabList.findIndex(e => `/${e.pagePath}` == `${url}.html`) > -1 ? 'switchTab' : 'redirectTo'
events.notIntercept = true
wx.p.router[routeName](url, events)
{ url, events } = this.setRouteData(targetPath),
routeName =
this.tabList.findIndex((e) => `/${e.pagePath}` == `${url}.html`) > -1
? "switchTab"
: "redirectTo";
events.notIntercept = true;
wx.p.router[routeName](url, events);
},
setRouteData(targetPath) {
let [url, query] = targetPath.split('?'),
events = {}
let [url, query] = targetPath.split("?"),
events = {};
if (query) {
let arr = query.split('&')
arr.map(e => {
let [key, val] = e.split('=')
if (val == 'false' || val == 'true') val = JSON.parse(val)
let arr = query.split("&");
arr.map((e) => {
let [key, val] = e.split("=");
if (val == "false" || val == "true") val = JSON.parse(val);
Object.assign(events, {
[key]: val
})
})
[key]: val,
});
});
}
return {
url,
events
}
}
})
\ No newline at end of file
events,
};
},
});
......@@ -34,26 +34,26 @@ Component({
},
// 获取用户会员信息
toCheckMember() {
wx.p.router.intercept(false).then(res => {
if (res) {
this.setData({
isMember: false,
})
} else {
wx.p.api.equityApi.checkOpenMember().then(res => {
let isMember = false
if (res.data && res.data.validitDate) {
res.data.time = new Date(res.data.validitDate).format('yyyy.MM.dd')
}
if (res.code == 0 && res.data) {
isMember = true
}
this.setData({
isMember
})
})
}
})
// wx.p.router.intercept(false).then(res => {
// if (res) {
// this.setData({
// isMember: false,
// })
// } else {
// wx.p.api.equityApi.checkOpenMember().then(res => {
// let isMember = false
// if (res.data && res.data.validitDate) {
// res.data.time = new Date(res.data.validitDate).format('yyyy.MM.dd')
// }
// if (res.code == 0 && res.data) {
// isMember = true
// }
// this.setData({
// isMember
// })
// })
// }
// })
},
// 获取门店会员卡信息
getMemberCardData() {
......
// pages/tab/mine/components/myOrder/myOrder.js
import { ORDER_LIST } from '~/constants/mine.js';
Component({
/**
* 组件的属性列表
......@@ -11,24 +13,7 @@ Component({
* 组件的初始数据
*/
data: {
orderList: Object.freeze([
{
text: "待支付",
imageUrl: "noPay",
},
{
text: "待发货",
imageUrl: "noTakeCommodity",
},
{
text: "待收货",
imageUrl: "takeCommodity",
},
{
text: "售后",
imageUrl: "aftermarket",
},
]),
orderList: ORDER_LIST,
},
/**
......@@ -36,11 +21,12 @@ Component({
*/
methods: {
goOrder(e) {
let { key } = e.currentTarget.dataset,
tabIndex = key || 0;
// 直接使用 ORDER_LIST 中的索引作为 tabIndex
const tabIndex = e.currentTarget.dataset.index || 0;
wx.p.router.go("/packageMine/pages/order/index/index", {
tabIndex,
});
},
},
});
});
\ No newline at end of file
......@@ -2,7 +2,7 @@
<view class="order-box box">
<view class="title">
我的订单
<view class="edit" bindtap="goOrder">
<view class="edit" bindtap="goOrder" data-index="0">
全部
<view class="arrow">
<glsx-image webp src="mine/right.png"></glsx-image>
......@@ -10,12 +10,14 @@
</view>
</view>
<view class="btnBox">
<view class="independentBox" wx:for="{{orderList}}" wx:key="index" bindtap="goOrder" data-key="{{index + 1}}">
<view class="order-img">
<glsx-image webp src="mine/{{item.imageUrl}}.png"></glsx-image>
<view class="independentBox" wx:for="{{orderList}}" wx:for-index="index" wx:for-item="item" wx:key="index" wx:if="{{index > 0}}">
<view bindtap="goOrder" data-code="{{item.code}}" data-index="{{index}}">
<view class="order-img">
<glsx-image webp src="mine/{{item.image}}.png"></glsx-image>
</view>
<text class="order-content">{{item.text}}</text>
<text class="order-number" wx:if="{{orderNumberList[index-1] != 0 && orderNumberList}}">{{orderNumberList[index-1]}}</text>
</view>
<text class="order-content">{{item.text}}</text>
<text class="order-number" wx:if="{{orderNumberList[index] != 0 && orderNumberList}}">{{orderNumberList[index]}}</text>
</view>
</view>
</view>
\ No newline at end of file
......@@ -31,7 +31,7 @@ Page({
wx.p.router.go(url);
},
async getOrderNumberList() {
const loginStatus = await wx.p.router.intercept(false);
const loginStatus = !wx.p.isLogin
if (loginStatus) return;
wx.p.api.mineApi.getOrderNumberList().then((res) => {
this.setData({
......@@ -46,38 +46,38 @@ Page({
},
// 获取用户会员信息
toCheckMember() {
wx.p.router.intercept(false).then((sid) => {
if (sid) {
this.setData({
isMember: false,
memberFlag: true,
});
} else {
wx.p.api.equityApi.checkOpenMember().then((res) => {
let flag = false,
identity = 0; // 普通会员3 银卡2 金卡1 非会员 0
if (res.data && res.data.validitDate) {
res.data.time = new Date(res.data.validitDate).format("yyyy.MM.dd");
}
if (res.data && res.data.endTime) {
res.data.endTime = new Date(res.data.endTime).format("yyyy.MM.dd");
}
if (res.code == 0 && res.data) {
flag = true;
identity = 3;
if (res.data && res.data.cardTypeSpecial)
identity = res.data.cardTypeSpecial;
}
wx.p.storage.set("isVIP", flag);
this.setData({
isMember: flag,
vipInfo: res.data,
identity,
memberFlag: true,
});
});
}
});
// wx.p.router.intercept(false).then((sid) => {
// if (sid) {
// this.setData({
// isMember: false,
// memberFlag: true,
// });
// } else {
// wx.p.api.equityApi.checkOpenMember().then((res) => {
// let flag = false,
// identity = 0; // 普通会员3 银卡2 金卡1 非会员 0
// if (res.data && res.data.validitDate) {
// res.data.time = new Date(res.data.validitDate).format("yyyy.MM.dd");
// }
// if (res.data && res.data.endTime) {
// res.data.endTime = new Date(res.data.endTime).format("yyyy.MM.dd");
// }
// if (res.code == 0 && res.data) {
// flag = true;
// identity = 3;
// if (res.data && res.data.cardTypeSpecial)
// identity = res.data.cardTypeSpecial;
// }
// wx.p.storage.set("isVIP", flag);
// this.setData({
// isMember: flag,
// vipInfo: res.data,
// identity,
// memberFlag: true,
// });
// });
// }
// });
},
/**
* 生命周期函数--监听页面显示
......
import router from "./router.js";
import routerBefore from './routerBefore'
module.exports={
module.exports = {
router,
routerBefore
}
\ No newline at end of file
/**
* 路由配置文件
* 管理需要登录权限的页面和免登录白名单页面
*/
// 需要登录才能访问的页面路径配置
export const authPages = [
'/packageMine/',
'/pages/mine/',
];
// 不需要拦截的页面路径配置
export const whiteList = [
'/pages/Login/Login',
'/pages/loading/loading',
'/pages/webView/webView',
'/packageMine/pages/order/index/index'
];
// tabBar页面路径配置
export const tabBarPages = [
'/pages/tab/index/index',
'/pages/tab/mall/index',
'/pages/tab/quity/index',
'/pages/tab/mine/index'
];
// 需要特殊处理的页面路径
export const specialPages = {
// webView页面
webView: '/pages/webView/webView',
// 首页
home: '/pages/tab/index/index',
// 登录页
login: '/pages/Login/Login'
};
export default {
authPages,
whiteList,
tabBarPages,
specialPages
};
\ No newline at end of file
import { authPages, whiteList, specialPages } from "./router.config.js";
const {
validateRoute,
isEmptyObject,
validateCallback,
validatePositiveNumber,
clearRouteParams,
} = require("./router.utils.js");
/**
* 路由管理类
* 提供统一的路由跳转控制,包括登录状态检查和路由传值功能
*/
class Router {
constructor(router) {}
/**获取页面对象实例 */
getPageInstance = (size = 1) => {
constructor() {
// 需要登录才能访问的页面路径配置
this.authPages = authPages;
// 不需要拦截的页面路径配置
this.whiteList = whiteList;
// 特殊页面路径
this.specialPages = specialPages;
}
/**
* 获取页面实例
* @param {number} size - 页面栈层级,默认为1(当前页面)
* @returns {Object} 页面实例
*/
getPageInstance(size = 1) {
const pages = getCurrentPages();
return pages[pages.length - size];
};
/**跳转至H5 */
jumpH5(url, notIntercept) {
if (notIntercept) wx.navigateTo({
url: `/pages/webView/webView?url=${encodeURIComponent(url)}`,
})
else this.intercept(url).then((response) => {
if (response) return;
wx.navigateTo({
url: `/pages/webView/webView?url=${encodeURIComponent(url)}`,
});
}
/**
* 跳转至H5页面
* @param {string} url - H5页面地址
*/
jumpH5(url) {
// 参数验证
if (!validateRoute(url)) {
return;
}
const shouldIntercept = this._interceptRoute(url);
if (shouldIntercept) return;
wx.navigateTo({
url: `${this.specialPages.h5}?url=${encodeURIComponent(url)}`,
});
}
/**
* 跳转到 tabBar 页面,并关闭其他所有非 tabBar 页面 ||
* 保留当前页面,跳转到应用内的某个页面。但是不能跳到 tabbar 页面。使用 $router.back() 可以返回到原页面。小程序中页面栈最多十层
* 保留当前页面,跳转到应用内的某个页面(不能跳转到 tabbar 页面)
* @param {string} route - 目标页面路径
* @param {Object} params - 传递给目标页面的参数
*/
go(route, events = {}) {
this._to(
route,
events,
'navigateTo',
(res) => events && res.eventChannel.emit('getData', events)
);
go(route, params = {}) {
// 参数验证
if (!validateRoute(route)) {
return;
}
this._navigateWithCheck(route, params, "navigateTo");
}
/**关闭所有页面,打开到应用内的某个页面 */
reLaunch(route, events = {}) {
this._to(route, events, 'reLaunch');
/**
* 关闭所有页面,打开到应用内的某个页面
* @param {string} route - 目标页面路径
* @param {Object} params - 传递给目标页面的参数
*/
reLaunch(route, params = {}) {
// 参数验证
if (!validateRoute(route)) {
return;
}
this._navigateWithCheck(route, params, "reLaunch");
}
/**关闭当前页面,跳转到应用内的某个页面。但是不允许跳转到 tabbar 页面。 */
redirectTo(route, events = {}) {
this._to(route, events, 'redirectTo');
/**
* 关闭当前页面,跳转到应用内的某个页面(不能跳转到 tabbar 页面)
* @param {string} route - 目标页面路径
* @param {Object} params - 传递给目标页面的参数
*/
redirectTo(route, params = {}) {
// 参数验证
if (!validateRoute(route)) {
return;
}
this._navigateWithCheck(route, params, "redirectTo");
}
/**
* 跳转到switchTab
* 跳转到 tabBar 页面,并关闭其他所有非 tabBar 页面
* @param {string} route - 目标tab页面路径
* @param {Object} params - 传递给目标页面的参数
*/
switchTab(route, events = {}) {
this._to(route, events, 'switchTab');
switchTab(route, params = {}) {
// 参数验证
if (!validateRoute(route)) {
return;
}
this._navigateWithCheck(route, params, "switchTab");
}
_to(route, events, to, success) {
getApp().globalData.ROUTE_QUERY = events
if (events.notIntercept) {
wx[to]({
url: route,
success
});
/**
* 带权限检查的导航方法
* @param {string} route - 目标页面路径
* @param {Object} params - 传递给目标页面的参数
* @param {string} method - 导航方法
*/
_navigateWithCheck(route, params, method) {
// 检查是否需要登录权限
const shouldIntercept = this._interceptRoute(route);
if (shouldIntercept) return;
// 执行具体的导航操作
this._executeNavigate(route, params, method);
}
/**
* 执行具体的导航操作
* @param {string} route - 目标页面路径
* @param {Object} params - 传递给目标页面的参数
* @param {string} method - 导航方法
*/
_executeNavigate(route, params, method) {
// 所有参数都通过全局变量传递
if (!isEmptyObject(params)) {
getApp().globalData.ROUTE_QUERY = params;
} else {
this.intercept().then((result) => {
!result && wx[to]({
url: route,
success
});
// 清空之前的参数
getApp().globalData.ROUTE_QUERY = {};
}
// 特殊处理switchTab
if (method === "switchTab") {
wx.switchTab({
url: route,
fail: (err) => {
console.error(`Navigation failed: ${err}`);
},
});
return;
}
// 其他跳转方式
wx[method]({
url: route,
fail: (err) => {
console.error(`Navigation failed: ${err}`);
},
});
}
/**prevPageSize = 1
* 返回上prevPageSize页
* callBack返回上prevPageSize页对象 */
back(callBack, prevPageSize = 1) {
let prevPage = this.getPageInstance(Number(prevPageSize) + 1);
if (callBack && 'function' === typeof callBack) callBack(prevPage);
/**
* 返回上一页
* @param {Function} callBack - 回调函数,返回上一页对象
* @param {Number} delta - 返回的页面数,默认为1
*/
back(callBack, delta = 1) {
// 参数验证
if (!validateCallback(callBack)) {
return;
}
if (!validatePositiveNumber(delta)) {
return;
}
let prevPage = this.getPageInstance(delta + 1);
if (callBack && typeof callBack === "function") callBack(prevPage);
wx.navigateBack({
delta: prevPageSize,
delta: delta,
}).catch((err) => {
console.warn("Navigate back failed, redirecting to home page:", err);
this.goHome();
});
}
/**
* 跳转到首页
*/
goHome() {
// 跳转到首页时清空参数
clearRouteParams();
wx.reLaunch({
url: '/pages/tab/index/index',
url: this.specialPages.home,
});
}
/**
* 在目标页面获取路由参数
* @param {Object} options - 页面 onLoad 函数的 options 参数(用于处理二维码等场景)
* @returns {Promise<Object>} 返回包含路由参数的Promise
*/
getRouterParams(options = {}) {
return new Promise((resolve, reject) => {
try {
// 从全局变量获取通过路由系统传递的参数
const globalParams = getApp().globalData.ROUTE_QUERY || {};
// 合并全局参数和页面参数(如二维码扫描传递的参数)
const params = Object.assign({}, options, globalParams);
if (!isEmptyObject(params)) {
// 清空已使用的全局参数
clearRouteParams();
resolve(params);
} else {
resolve({});
}
} catch (err) {
console.error("Get router params error:", err);
reject(err);
}
});
}
/**获取上一个页面传的数据 */
getData(callBack) {
const data = this.getPageInstance().getOpenerEventChannel();
if (Object.keys(data).length !== 0)
data.on('getData', (res) => callBack(res));
/**
* 检查路由是否需要登录权限
* @param {string} route - 路由路径
* @returns {boolean} 是否需要登录权限
*/
_requiresAuth(route) {
// 白名单中的页面不需要登录
if (this.whiteList.some((path) => route.startsWith(path))) {
return false;
}
// 检查是否在需要登录的页面列表中
return this.authPages.some((path) => route.startsWith(path));
}
/**
*
* @param {*} auto 是否自动跳转到登录,默认自动跳转
* @param {*} callBack true未登录 false已登录
* 路由拦截检查
* @param {string} route - 目标路由
* @returns {boolean} 是否需要拦截(true表示需要拦截,false表示不需要)
*/
async intercept(auto = true) {
const authStatus = wx.$LoginStatus
if (authStatus) {
if (auto) wx.navigateTo({
url: '/pages/Login/Login',
})
return true;
} else {
_interceptRoute(route) {
// 检查是否需要登录权限
if (!this._requiresAuth(route)) {
// 不需要登录,放行
return false;
}
// 检查登录状态
const isLogin = wx.p.isLogin;
if (isLogin) {
// 已登录,放行
return false;
} else {
// 未登录,跳转到登录页面
wx.navigateTo({
url: this.specialPages.login,
});
return true; // 需要拦截
}
}
}
export default new Router();
\ No newline at end of file
export default new Router();
/**
* 验证路由路径是否为非空字符串
* @param {string} route - 路由路径
* @returns {boolean} 验证结果,true表示验证通过
*/
function validateRoute(route) {
if (typeof route !== "string" || !route) {
console.error("Route must be a non-empty string");
return false;
}
return true;
}
/**
* 判断对象是否为空对象
* @param {Object} obj - 待检测的对象
* @returns {boolean} 检测结果,true表示是空对象
*/
function isEmptyObject(obj) {
return !obj || Object.keys(obj).length === 0;
}
/**
* 验证参数是否为函数
* @param {*} callback - 待验证的参数
* @returns {boolean} 验证结果,true表示是函数
*/
function validateCallback(callback) {
if (callback && typeof callback !== "function") {
console.error("Callback must be a function");
return false;
}
return true;
}
/**
* 验证参数是否为正数
* @param {*} delta - 待验证的参数
* @returns {boolean} 验证结果,true表示是正数
*/
function validatePositiveNumber(delta) {
if (typeof delta !== "number" || delta < 1) {
console.error("Delta must be a positive number");
return false;
}
return true;
}
/**
* 清理路由参数
*/
function clearRouteParams() {
getApp().globalData.ROUTE_QUERY = {};
}
module.exports = {
validateRoute,
isEmptyObject,
validateCallback,
validatePositiveNumber,
clearRouteParams
};
\ No newline at end of file
class RouterBefore {
constructor(options) {
console.log('---------------- 路由初始化 ----------------')
this.initPageProxy()
}
/**监听页面 */
pageLeaveProxy(thisPage) {
let onLoad = thisPage.onLoad,
onShow = thisPage.onShow
thisPage.onLoad = function () {
const event = getApp().globalData.ROUTE_QUERY
const userInfo = wx.p.storage.get('userInfo')
let options = {
...event,
...arguments[0]
}
getApp().globalData.ROUTE_QUERY = {}
this.setData({
userInfo
})
onLoad && onLoad.apply(this, [options]), (this.options = options)
}
thisPage.onShow = function () {
const userInfo = wx.p.storage.get('userInfo')
onShow && onShow.apply(this, arguments), (this.setData({
userInfo
}))
}
}
/**全局注册事件 */
initPageProxy() {
let thisPage = Page
let _this = this
Page = function (el) {
try {
el || (el = {}), _this.pageLeaveProxy(el), thisPage.apply(this, arguments)
} catch (el) {
thisPage.apply(this, arguments)
}
}
// 不再重写Page函数,避免潜在风险
}
}
export default new RouterBefore()
\ No newline at end of file
class Bus {
constructor() {
this.events = {}
constructor() {
this.events = {};
}
/**
* 订阅事件
* @param {string} event - 事件名称
* @param {Function} callback - 回调函数
*/
on(event, callback) {
if (typeof event !== 'string') {
console.error('Event name must be a string');
return;
}
on(Event, cb) {
if(this.events[Event]) {
this.events[Event].push(cb);
} else {
this.events[Event] = [cb];
}
// 如果是匿名函数就给用户个警告
if(!cb.name) {
console.warn('on 接口的 handler 参数推荐使用具名函数。具名函数可以使用 off 接口取消订阅,匿名函数无法取消订阅。')
}
if (typeof callback !== 'function') {
console.error('Callback must be a function');
return;
}
emit(Event, obj) {
if(!this.events[Event]) return
this.events[Event].forEach(cb => {
cb(obj)
})
if (this.events[event]) {
this.events[event].push(callback);
} else {
this.events[event] = [callback];
}
off(Event,cb) {
if(!this.events[Event]) return
const index = this.events[Event].findIndex(item => item === cb);
if (index === -1) {
// console.error(new Error('该 handle 没有订阅者,取消订阅失败'));
return;
}
this.events[Event].splice(index, 1);
// 如果是匿名函数就给用户个警告
if (!callback.name) {
console.warn('on 接口的 handler 参数推荐使用具名函数。具名函数可以使用 off 接口取消订阅,匿名函数无法取消订阅。');
}
// 给这个类加一个静态方法,用来判断这个类之前有没有生成过对象
static getInstance() {
if (!Bus.instance) {
Bus.instance = new Bus()
}
/**
* 触发事件
* @param {string} event - 事件名称
* @param {*} data - 传递给回调函数的数据
*/
emit(event, data) {
if (!this.events[event]) return;
this.events[event].forEach(callback => {
if (typeof callback === 'function') {
callback(data);
}
return Bus.instance;
});
}
/**
* 取消订阅事件
* @param {string} event - 事件名称
* @param {Function} callback - 要取消的回调函数
*/
off(event, callback) {
if (!this.events[event]) return;
if (typeof callback !== 'function') {
console.error('Callback must be a function');
return;
}
const index = this.events[event].findIndex(item => item === callback);
if (index !== -1) {
this.events[event].splice(index, 1);
}
}
/**
* 获取单例实例
* @returns {Bus} Bus类的单例实例
*/
static getInstance() {
if (!Bus.instance) {
Bus.instance = new Bus();
}
return Bus.instance;
}
// 导出这里返回 Bus 类静态 getInstance 的执行结果
export default Bus.getInstance();
\ No newline at end of file
}
// 导出Bus类的单例实例
export default Bus.getInstance();
\ No newline at end of file
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!