浏览代码

refactor(util&index): 优化防抖与菜单渲染逻辑

1. 将防抖timer收敛进闭包避免全局变量污染
2. 提取前9个菜单为计算属性menuTop9优化渲染
3. 添加菜单缓存读写逻辑,加载失败时降级使用缓存
4. 调整生命周期中防抖调用的错误捕获
allen 1 周之前
父节点
当前提交
e886bf9b00
共有 2 个文件被更改,包括 25 次插入12 次删除
  1. 24 12
      pages/index/index.vue
  2. 1 0
      util/anitthro.js

+ 24 - 12
pages/index/index.vue

@@ -56,7 +56,7 @@
 		<view class="functionbox">
 			
 			<view class="functionbox_text">
-				<view class="functionbox_text_item" @click="tabfunction(0,item)" v-if="index < 9" v-for="(item,index) in menuList" :key="index">
+				<view class="functionbox_text_item" @click="tabfunction(0,item)" v-for="(item,index) in menuTop9" :key="index">
 					<image :src="item.app_menu_icon" mode="" class="itemimg">
 					</image>
 					<view class="icon_text"> {{ getSlice(item.purview_name) }} </view>
@@ -211,7 +211,12 @@
 				}
 			},
 		},
-		methods: {
+		computed: {
+		menuTop9() {
+			return (this.menuList || []).slice(0, 9);
+		}
+	},
+	methods: {
 			handlePopupClose(){
 				console.log('弹窗已关闭')
 			},
@@ -267,8 +272,20 @@
 					data: JSON.stringify(myuid),
 				});
         this.menuList = menuList || [];
+			uni.setStorage({
+				key: 'menuList',
+				data: JSON.stringify(menuList || []),
+			});
 			},
-			tabfunction(index,item) {
+			loadMenuFromCache() {
+			try {
+				const cached = uni.getStorageSync('menuList');
+				if (cached) this.menuList = JSON.parse(cached) || [];
+			} catch (e) {
+				console.error('读取 menuList 缓存失败:', e);
+			}
+		},
+		tabfunction(index,item) {
 				const purId = item?.pur_id || '';
 				if (purId == 25) {
 					uni.navigateTo({
@@ -411,20 +428,15 @@
 			} else {
 				this.hello = '下午好!';
 			}
-			Debounce(() => {
-				this.getUserlogin();
-			}, 500)();
 			this.checkLocationPermission(true); // 首次加载弹框提醒
 		},
-		created() {
-			Debounce(() => {
-				this.getUserlogin();
-			}, 500)();
-		},
 		onShow() {
 			this.loadTF = false;
 			Debounce(() => {
-				this.getUserlogin();
+				this.getUserlogin().catch(e => {
+					console.error('getUserlogin 失败:', e);
+					this.loadMenuFromCache();
+				});
 			}, 500)();
 			this.checkLocationPermission();
 		},

+ 1 - 0
util/anitthro.js

@@ -2,6 +2,7 @@ let timer1 = null; //防抖,
 let timer2 = null; //节流  
 function Debounce(fn, t) {//防抖
 	let delay = t || 500;
+	let timer1 = null; // 收敛进闭包:每个防抖实例独立计时,避免全局 timer1 被其它调用 clearTimeout 互相取消
 	return function () {  
 	    let args = arguments;  
 	    // let timer1 = null