大家平时写axios请求的时候,重复代码快写吐了吧,类似下面这种。

下面是我封装的$tryCatch方法,可以自动抛出错误提示,自动加载loading。

import Vue from "vue";
// func 请求方法 | data 请求参数 | target 区域显示dom | useSuccMessage 使用成功提示
export function tryCatch(func, data, target, useSuccMessage = true) {
  return new Promise(async (resolve, reject) => {
    const loading = Vue.prototype.$loading({
      lock: true,
      target // 设置加载动画区域
    })
    try {
      let res = await func(data)
      if (res && res.header.returnCode === "0") {
        if (useSuccMessage) {
          Vue.prototype.$message({
            message: res.header.msg,
            type: "success",
          });
        }
        resolve(res)
      } else if (res.header.returnCode === "1") {
        Vue.prototype.$message.error(res.header.msg);
        reject(res)
      }
    } catch (err) {
      loading.close()
      reject(err)
    } finally {
      loading.close()
    }
  })
}

用之前在main.js中全局配置一下,这样在组件中就可以通过this.$tryCatch调用。

// tryCatch通用方法引入,全局配置
import { tryCatch } from '@/assets/js/ex-common.js'
Vue.prototype.$tryCatch = tryCatch;

用法如下:

methods: {
  async handleSearch() {
    let data = this.$refs.search.ruleForm;
    try {
      let res = await this.$tryCatch(findPage, data, this.$refs.smallTable.$el, false)
      this.tableData = res.data.records;
      this.total = res.data.total;
      this.current = res.data.current
      this.pages = res.data.pages
    } catch (err) {
      console.log(err)
    }
  }
},

 

解释:

 注意:handleSearch方法调用的时候只能在mounted中调用,因为mounted钩子中才能获取到loading动画需要的dom元素。

完事!希望大家都能少写一些重复代码,多开小差。

 

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐