Vue下axios同步问题

700 阅读1分钟

解决axios同步问题

  • 我们在使用ajax时可以通过配置属性
    async: false 进行同步
  • 但axios本身并不像ajax一样可以配置属性进行同步,所以我们需要借助 async,await 进行同步;
  • 这里以Vue为例:
    因为await必须在async函数中才能使用,所以最外面的函数必须使用async修饰;
    逻辑2 只有当res接收到axios的返回结果时才会执行,此时axios达到同步的目的;
     // 使用await进行同步 res接收返回结果
     async getDicts() {
        // 逻辑1
        let res = await this.getDicts("lh_credential_type");
        // 逻辑2
     }  
    
  • 完整数据字典获取示例:
    这里需必须要先获取数据字典,然后再获取用户信息 ,完成前面两部之后才能使用翻译方法进行翻译,所以这里必须要使用同步先进行前面两个步骤;
     created() {
          // 从路由获取参数
          this.user.userId = this.$route.query.id;
          // 这是一个同步方法
          this.getUserDetail();
        },
     methods: {
      // 根据用户id获取用户详情 需要同步执行
      async getUserDetail() {
        this.loading = true;
        // 获取数据字典 使用await修饰axios方法进行同步,响应结果使用res接收
        // 因为使用了 await 同步 所以接收到返回结果后才会往下执行
        let res = await this.getDicts("lh_credential_type");
        this.credentialTypeOptions = res.data;
        res = await this.getDicts("lh_marriage_state");
        this.marrigeStateOptions = res.data;
        res = await this.getDicts("sys_yes_no");
        this.parentStateOptions = res.data;
        res = await this.getDicts("sys_user_sex");
        this.sexOptions = res.data;
        res = await this.getDicts("lh_nation");
        this.nationOptions = res.data;
        res = await this.getDicts("lh_life_state");
        this.lifeStateOptions = res.data;
        // 获取用户信息 以上执行完之后才会执行这里
        res = await getUser(this.user.userId);
        this.user = res.data;
        // 调用字典翻译方法,翻译后直接赋到原值上
        this.credentialTypeFormat(this.user.credentialType);
        this.marriageStateFormat(this.user.marriageState);
        this.parentStateFormat(this.user.parentState);
        this.sexFormat(this.user.sex);
        this.nationFormat(this.user.nation);
        this.lifeStateFormat(this.user.lifeState);
        this.mergeHeightWeight();
        this.loading = false;
      }