浏览代码

代码优化

@dongkboy 3 周之前
父节点
当前提交
9338210ae3
共有 5 个文件被更改,包括 138 次插入50 次删除
  1. 9 0
      .hbuilderx/launch.json
  2. 10 3
      config/api.js
  3. 1 1
      config/login.js
  4. 102 35
      pages/index/index.vue
  5. 16 11
      plugins/request/index.js

+ 9 - 0
.hbuilderx/launch.json

@@ -0,0 +1,9 @@
+{
+    "version" : "1.0",
+    "configurations" : [
+        {
+            "playground" : "standard",
+            "type" : "uni-app:app-android"
+        }
+    ]
+}

+ 10 - 3
config/api.js

@@ -51,6 +51,7 @@ $http.requestEnd = function(options, resolve) {
 let loginPopupNum = 0;
 //所有接口数据处理(此方法需要开发者根据各自的接口返回类型修改,以下只是模板)
 $http.dataFactory = async function(res) {
+	console.log(res);
 	if (res.response.statusCode && res.response.statusCode == 200) {
 		let httpData = res.response.data;
 		if (typeof(httpData) == "string") {
@@ -60,6 +61,15 @@ $http.dataFactory = async function(res) {
 		//判断数据是否请求成功
 		// 判断数据是否请求成功
 		if (httpData.code === 401 || httpData.code === "401") { // 仅处理401情况
+			// 已在登录页时静默处理:不弹“登录已失效”,避免登录页上反复弹窗
+			let pages = getCurrentPages();
+			let currentPage = pages[pages.length - 1];
+			if (currentPage && currentPage.route === 'pages/login/login') {
+				return Promise.reject({
+					statusCode: 0,
+					errMsg: (httpData.info || httpData.msg)
+				});
+			}
 			if (loginPopupNum <= 0) {
 				loginPopupNum++;
 				uni.showModal({
@@ -139,8 +149,5 @@ $http.requestError = function(e) {
 			duration: 2000
 		});
 	}
-	if (e.requestId && pendingCallbacks[e.requestId]) {
-		pendingCallbacks[e.requestId]();
-	}
 }
 export default $http;

+ 1 - 1
config/login.js

@@ -122,7 +122,7 @@ async function getStaffStatus(userId) {
 
 	store.commit('setUserModules', {
 		title: 'userStatus',
-		data: status
+		data: res.data
 	})
 	return true;
 }

+ 102 - 35
pages/index/index.vue

@@ -183,6 +183,10 @@ export default {
 			carTypeShow: false, //选择车型
 
 			tenantOrglist: [], //租户机构列表
+			tenantLoaded: false, //机构列表是否已加载(防止 onShow 补加载与 onLoad 重复执行)
+			tenantLoading: false, //机构列表是否加载中(防重入)
+			historyLoaded: false, //历史报价车牌是否已加载
+			loadedToken: '', //数据加载时的token(用于检测登录账号变化,401重登/换账号时重置并重载)
 			deptradiovalue: '',
 			deptradioName: '',
 			licenseActiveName: '晋', //车牌选中
@@ -217,49 +221,100 @@ export default {
 		}
 	},
 	async onShow() {
-		await this.getDicType("car_kind_code"); //车辆种类
 		if (!store.state.token) {
-			uni.navigateTo({
-				url: "/pages/login/login"
-			});
+			// 未登录先跳登录页,避免在首页发起需要登录态的请求;已在登录页时不重复跳转
+			let pages = getCurrentPages();
+			let currentPage = pages[pages.length - 1];
+			if (!(currentPage && currentPage.route === 'pages/login/login')) {
+				uni.navigateTo({
+					url: "/pages/login/login"
+				});
+			}
+			return;
 		}
-
+		// 登录账号变化(401重登/换账号)时重置加载标志并清空旧数据,重新拉取
+		// 注意:不重置 tenantLoading,避免打断执行中 onLoad 的防重入(否则会重复请求/重复签到)
+		if (this.loadedToken !== store.state.token) {
+			this.tenantLoaded = false;
+			this.historyLoaded = false;
+			this.tenantOrglist = [];
+			this.historicalVehicle = [];
+			this.bannerList = [];
+			this.deptradiovalue = '';
+			this.deptradioName = '';
+		}
+		// 已登录但首页数据未加载(如未登录时进入过首页后再登录,onLoad 不会重新执行),补加载
+		if (!this.tenantLoaded) {
+			await this.onLoad();
+		} else if (!this.historyLoaded) {
+			this.loadHistoryQuote(); //机构已加载但历史车牌失败过,单独补
+		}
+		await this.getDicType("car_kind_code"); //车辆种类
 	},
 	async onLoad() {
-		let res = await this.$http.post('/userInfo/getTenantList'); //获取机构列表
-		if (res.code == '200' && res.data && res.data.length) {
-			if (res.data.length > 1) {
-				this.tenantOrglist = res.data;
-				if (!store.state.system_code) {
-					this.deptSelectShow = true; //多个租户弹窗选择
-				} else {
-					this.deptradiovalue = store.state.system_code;
-					this.deptradioName = store.state.system_Name;
+		if (!store.state.token) {
+			return; // 未登录不发请求(onShow 会跳转登录页),避免 getTenantList 等接口 401 弹“登录已失效”
+		}
+		if (this.tenantLoading || this.tenantLoaded) {
+			return; // 防重入:加载中或已加载过则不再执行,避免重复请求/重复签到
+		}
+		const loadToken = store.state.token; // 快照本次加载的token,完成时校验账号是否已变化
+		this.tenantLoading = true;
+		try {
+			let res = await this.$http.post('/userInfo/getTenantList'); //获取机构列表
+			if (res.code == '200') {
+				if (res.data && res.data.length) {
+					if (res.data.length > 1) {
+						this.tenantOrglist = res.data;
+						if (!store.state.system_code) {
+							this.deptSelectShow = true; //多个租户弹窗选择
+						} else {
+							this.deptradiovalue = store.state.system_code;
+							this.deptradioName = store.state.system_Name;
+						}
+					} else {
+						//单个租户赋值第一个(仅组件内数据,写store/签到等副作用在校验通过后执行)
+						this.tenantOrglist = res.data;
+						this.deptradiovalue = res.data[0].systemCode;
+						this.deptradioName = res.data[0].deptName;
+					}
 				}
-			} else {
-				//单个租户赋值第一个
-				this.tenantOrglist = res.data;
-				this.deptradiovalue = res.data[0].systemCode;
-				this.deptradioName = res.data[0].deptName;
-				store.commit('setUserModules', {
-					title: 'system_code',
-					data: this.tenantOrglist[0].systemCode
-				})
-				store.commit('setUserModules', {
-					title: 'system_Name',
-					data: this.tenantOrglist[0].sysName
-				})
-				await this.bannerquery(); //获取轮播图
-				await this.getUserInfo(); //获取人员信息
-				let res1 = await this.$http.post('/signIn/doSignIn',)
+				// 账号校验前置:加载期间账号已变化则放弃并清理,避免旧账号数据污染store/重复签到
+				if (store.state.token !== loadToken) {
+					this.tenantOrglist = [];
+					this.deptradiovalue = '';
+					this.deptradioName = '';
+					this.deptSelectShow = false;
+					return;
+				}
+				// 校验通过后才执行写store与签到等副作用操作
+				if (res.data && res.data.length === 1) {
+					store.commit('setUserModules', {
+						title: 'system_code',
+						data: this.tenantOrglist[0].systemCode
+					})
+					store.commit('setUserModules', {
+						title: 'system_Name',
+						data: this.tenantOrglist[0].sysName
+					})
+					await this.bannerquery(); //获取轮播图
+					await this.getUserInfo(); //获取人员信息
+					await this.$http.post('/signIn/doSignIn')
+				}
+				// 整条初始化链成功后才置位(任一环节失败则不置位,onShow 下次可重试)
+				this.tenantLoaded = true;
+				this.loadedToken = loadToken;
 			}
-
+		} catch (e) {
+			// 静默:401 由 dataFactory 统一处理,网络异常不中断;tenantLoaded 保持 false,下次 onShow 可重试
+		} finally {
+			this.tenantLoading = false;
 		}
-		let res1 = await this.$http.get('/supplementOrder/getHistoryQuote'); //获取历史报价车牌
-		if (res1.code == '200') {
-			this.historicalVehicle = res1.data;
+		try {
+			await this.loadHistoryQuote(); //获取历史报价车牌
+		} catch (e) {
+			// 静默:历史报价车牌加载失败不影响主流程
 		}
-
 	},
 	beforeCreate() {
 		// setTimeout(() => {
@@ -268,6 +323,18 @@ export default {
 	},
 	methods: {
 		...mapMutations(['activelicenseNo']),
+		//获取历史报价车牌(独立方法,失败后 onShow 可单独重试)
+		async loadHistoryQuote() {
+			const loadToken = store.state.token; // 快照token,完成时校验账号是否已变化
+			let res1 = await this.$http.get('/supplementOrder/getHistoryQuote');
+			if (res1.code == '200') {
+				if (store.state.token !== loadToken) {
+					return; // 加载期间账号已变化,放弃(数据属于旧账号)
+				}
+				this.historicalVehicle = res1.data;
+				this.historyLoaded = true;
+			}
+		},
 		arr() {
 			uni.navigateTo({
 				url: '/pages/reward/benefitPackage'

+ 16 - 11
plugins/request/index.js

@@ -9,25 +9,32 @@ const whiteList = [
 	"/pages/login/xieyi",
 	"/pages/login/mimi",
 	"/pages/index/index",
-	"pages/quote/paymentCode"
-
+	"/pages/quote/paymentCode"
 ];
 //白名单 不需要登录的页面路径组成的数组
 function hasPermission(url) {
-	// 在白名单中或有token,直接跳转
-	if (whiteList.indexOf(url) !== -1 || store.state.token) {
+	// 去掉url上的查询参数(如扫码注册携带的邀请码等),再做白名单匹配
+	const path = url.split("?")[0];
+	// 在白名单中或有token,直接放行
+	if (whiteList.indexOf(path) !== -1 || store.state.token) {
 		return true;
 	}
-	return true;
+	return false;
+}
+
+// 拦截时先清理登录态(含过期token),再跳登录页,避免过期token残留导致登录页请求401
+function goLogin() {
+	store.commit("emptyUserInfo");
+	uni.reLaunch({
+		url: "/pages/login/login",
+	});
 }
 
 uni.addInterceptor("navigateTo", {
 	// 页面跳转前进行拦截, invoke根据返回值进行判断是否继续执行跳转
 	invoke(e) {
 		if (!hasPermission(e.url)) {
-			uni.reLaunch({
-				url: "/pages/login/login",
-			});
+			goLogin();
 			return false;
 		}
 		return true;
@@ -39,9 +46,7 @@ uni.addInterceptor("switchTab", {
 	// tabbar页面跳转前进行拦截
 	invoke(e) {
 		if (!hasPermission(e.url)) {
-			uni.reLaunch({
-				url: "/pages/login/login",
-			});
+			goLogin();
 			return false;
 		}
 		return true;