Skip to content

JavaScript定时器

  • 定时器需要在组件/页面销毁前销毁,否则存在定时器运行时,关闭组件/页面,定时器依旧在运行的问题。

代码示例:

vue
<!-- 下级报表管理审核-头部区域 -->
<template>
  <!-- 容器 -->
  <div class="pfs-gfa-audit-manage-header fix">
    <!-- 右侧区域 -->
    <div class="r">
      <el-button size="small" @click="onAudit" v-obPoint="{vm: this, name: '重新运行审核'}">
        <v-svg type="bs-reset"></v-svg> 重新运行审核
      </el-button>
    </div>
  </div>
</template>
<script>
import { mapGetters } from 'vuex';
import { GET_LOGIN_INFO } from '@/store/login';
import fetch from '@/config/fetch';
import util from '@/assets/js/util';
import {
  PAGE_TYPE,
  CONTENT_TYPE,
} from '@/modules/pfs/pfs-gfa/pfs-gfa-audit-manage/constant';

export default {
  props: {
    contextInfo: Object, //上下文数据
    pageType: String, //页面显示类型
    contentType: String, //内容区域显示类型
    agencyInfo: Object, //当前选的单位信息
    agencyFilter: Array,  //已过滤的单位数据
    setContentType: Function, //设置内容区域显示类型
    fillCause: Function, //填写原因
    getContentType: Function, //当前有效的内容区域显示类型
  },
  data() {
    return {
      timer: null, //TODO:状态数据中声明定时器对象
      PAGE_TYPE,
      CONTENT_TYPE,
    };
  },
  methods: {
    /**
     * 获取审核结果
     */
    getAuditResult(cacheKey) {
      return new Promise((resolve, reject) => {
        let flag = true;
        this.timer = setInterval(() => {
          if (flag) {
            flag = false;
            let url = this.pageType === PAGE_TYPE.AGENCY ? `/gfa/fr/gfa/rpt/getCheckMsg?cacheKey=${cacheKey}` : `/gfa/fr/gfa/rpt/getAuditMsg/${cacheKey}`;
            fetch
              .get(url)
              .then(({ data }) => {
                if (data.isDone === 1) {
                  clearInterval(this.timer);
                  this.timer = null;
                  return resolve();
                } else {
                  this.$loading(data.msg);
                }
              })
              .catch((err) => {
                clearInterval(this.timer);
                this.timer = null;
                return reject(err);
              })
              .finally(() => {
                flag = true;
              });
          }
        }, 2000);
      });
    },
    /**
     * 构建运行审核参数
     * 1、初始化默认参数
     * 2、根据页面显示类型构建对应数据
     */
    buildResetParams(formulaIds) {
      let url = '';
      let {
        agencyCode,
        agencyName,
        acctPeriod,
        perdType,
        transType,
        lastyearCode,
        taskId,
        fiscalYear,
        dwType,
        mofDivCode,
      } = this.contextInfo;
      let params = {
        acctPeriod,
        perdType,
        transType,
        taskId,
        fiscalYear,
        year: fiscalYear,
        lastyearCode,
        createUserCode: this.GET_LOGIN_INFO.userCode,
        createUser: this.GET_LOGIN_INFO.userName,
        userCode: this.GET_LOGIN_INFO.userCode,
        userName: this.GET_LOGIN_INFO.userName,
        dataVer: 0,
        receiveAgencyCode: agencyCode,
        receiveAgencyName: agencyName,
        receiveDwType: dwType,
        receiveMofDivCode: mofDivCode,
      };
      if (this.pageType === PAGE_TYPE.AGENCY) {
        url = '/gfa/fr/gfa/rpt/recheck';
        params.agencyCode = this.agencyInfo.agencyCode;
        params.agencyName = this.agencyInfo.agencyName;
        params.mofDivCode = this.agencyInfo.mofDivCode;
        params.checkList = [
          CONTENT_TYPE.INTEGRITY,
          CONTENT_TYPE.FORMULA_AUDIT,
          CONTENT_TYPE.QUERY_TEMPLATE,
          CONTENT_TYPE.RECONCILIATION,
          CONTENT_TYPE.CONFORMANCE_CHECK,
        ];
      } else {
        url = '/gfa/fr/gfa/rpt/recheckList';
        params.agencyCode = agencyCode;
        params.agencyName = agencyName;
        params.mofDivCode = this.contextInfo.mofDivCode;
        params.checkList = [this.contentType];
        params.dwType = dwType;
        params.agencyFilter = this.agencyFilter.map((e) => e.agencyCode);
        params.formulaIds = formulaIds; // 只有按类别并且是公式审核才会有值
      }
      return { url, params };
    },
    /**
     * 重新运行审核
     * 1、如果是按类别并且是公式审核,弹窗公式审核窗口选择公式
     * 2、构建运行审核参数
     * 3、运行审核
     * 4、获取进度条状态
     * 5、提示用户,并触发页面重置事件
     */
    async onAudit() {
      try {
        let formulaIds = [];
        if (this.pageType === PAGE_TYPE.CATEGORY && this.contentType === CONTENT_TYPE.FORMULA_AUDIT) {
          formulaIds = await this.$refs.allFormulaAudit.open();
        }
        this.$loading();
        let { url, params } = this.buildResetParams(formulaIds);
        let { data } = await fetch.post(url, params);
        await this.getAuditResult(data.cacheKey);
        this.$alert('审核完成,将重新获取页面数据!', '', {
          confirmButtonText: '确定',
          showClose: false,
          callback: () => {
            // TODO:审核完成之后,重新获取页面数据
          },
        });
      } catch (err) {
        console.error(err);
        this.$message({
          type: 'error',
          message: err.msg,
        });
      } finally {
        this.$loadingClose();
      }
    },
  },
  computed: {
    ...mapGetters([GET_LOGIN_INFO]),
  },
  /**
   * 销毁定时器
   */
  beforeDestroy() {
    clearInterval(this.timer);
    this.timer = null;
  },
};
</script>
<style lang="scss" scoped>
@import '~@/assets/style/variables.scss';
.pfs-gfa-audit-manage-header {
  height: 50px;
  margin-top: 5px;
  padding: 10px;
  box-sizing: border-box;
  background: $-bs-bg-white;
  border-radius: $-bs-border-radius;
  ::v-deep .el-radio-button {
    .el-radio-button__inner {
      position: relative;
      padding: 8px 5px;
      font-size: 13px;
      .node-badge {
        position: absolute;
        right: -2px;
        top: -15px;
        min-width: 12px;
        padding: 4px;
        background: $-bs-color-red;
        font-size: 12px;
        color: $-bs-color-white;
        border-radius: 100%;
      }
    }
  }
  ::v-deep .el-button--small {
    padding: 8px 5px;
    span {
      font-size: 13px;
    }
  }
}
</style>