• 在 Vue 的 mounted 钩子函数中使用异步函数是否会有风险需要考虑


    主要的区别在于:

    异步函数 - 使用 await,执行时不会blocking,但获取数据时组件已渲染
    同步函数 - 直接返回数据,组件渲染需等待执行结束

    使用异步函数的潜在风险:
    如果异步请求时间过长,组件会先渲染,导致页面空白或显示不正确
    获取数据失败时,无法准确得到失败信息来源

    同步函数的优点:
    组件渲染会等待数据就绪,避免空状态问题
    获取数据失败会直接抛出异常,可以明确错误来源
    所以,如果获取标签配置数据非关键,可以使用异步函数,但需要注意加载状态。

    如果是关键数据,建议使用同步函数获取,甚至提前获取,以免影响组件的渲染。

    需要根据应用特点来权衡异步带来的好处和风险。

    CR自己的代码

    async mounted() {
    
    	if (localStorage.getItem('tagConfig')) {
    	
    		this.tagConfig = JSON.parse(localStorage.getItem('tagConfig'));
    	
    	} else {
    
    		const tagConfig = (await getComListEnums()).data;
    	
    		localStorage.setItem('tagConfig', JSON.stringify(tagConfig));
    	
    		this.tagConfig = tagConfig;
    	}
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

    一个很简单的逻辑 先去判断本地缓存里有没有数据存储,有就取本地数据
    没有就取请求接口并且储存 但是考虑到异步函数是否会有风险 决定改为同步

    主要改动:
    getFreshConfig 改为同步函数,直接返回结果
    不需要 async/await
    组件渲染会等待配置就绪
    同步函数也更容易处理错误。

    这个修改可以避免异步函数的一些风险,确保组件只在数据获取完成后才渲染。

    // data中声明tagConfig
    
    mounted() {
      try {
        const cachedConfig = localStorage.getItem('tagConfig')
        const cacheData = JSON.parse(cachedConfig)
    
        if (cacheData) {
          this.tagConfig = cacheData 
        } else {
          // 获取最新配置(同步)
          const result = getFreshConfig()  
          const freshConfig = result
    
          // 缓存
          localStorage.setItem('tagConfig', JSON.stringify(freshConfig))
          
          this.tagConfig = freshConfig
        }
    
      } catch (err) {
        // 处理错误
      }
    },  
    
    methods: {
      // 同步函数
      getFreshConfig() { 
        const result = getComListEnums()
        return result.data
      }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
  • 相关阅读:
    Day23--前后端分离项目中如何使用 Vue.js 和 Axios 加载 WebServlet 生成的验证码图片
    Human-level control through deep reinforcement learning
    Kubernetes--K8s基础详解
    学校网页设计成品 基于HTML+CSS+JavaScript仿山东财经大学官网 学校班级网页制作模板 校园网页设计成品
    TikTok运营指南:如何通过TikTok广告实现社媒引流?
    [go 反射] 函数
    笔记:GO1.19 带来的优化(重新编译juicefs)
    WebRTC 日志
    Linux 简介
    python中的模块与包
  • 原文地址:https://blog.csdn.net/weixin_47353884/article/details/132871576