Commit 526d78e1 by liimin

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

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