Vue.js 实现下载模板和导入模板、数据比对功能核心实现。

发布于:2025-04-09 ⋅ 阅读:(26) ⋅ 点赞:(0)

在前端开发中,数据比对是一个常见需求,尤其在资产管理等场景中。本文将基于 Vue.js 和 Element UI,通过一个简化的代码示例,展示如何实现“新建比对”和“开始比对”功能的核心部分。

一、功能简介

我们将聚焦两个核心功能:

  1. 新建比对:打开上传对话框,允许用户选择文件。
  2. 开始比对:上传文件并调用后端接口进行数据比对,同时展示进度。

以下是逐步拆分的实现细节。


二、核心代码实现

1. 新建比对

“新建比对”功能通过一个按钮触发,打开文件上传对话框。

模板部分

在页面中添加按钮和上传对话框:

<template>
  <MainCard>
    <!-- 新建比对按钮 -->
    <el-row>
      <el-col :span="24">
        <el-button type="primary" @click="openImportDialog" class="mg20">新建比对</el-button>
      </el-col>
    </el-row>

    <!-- 导入对话框 -->
    <el-dialog title="数据比对" :visible.sync="visible" width="800px" append-to-body>
      <div class="importDialogBody">
        <p class="title">数据上传</p>
        <div class="text-box">
          <el-upload
            ref="upload"
            :limit="limit"
            :on-remove="handleRemove"
            :before-upload="handleBeforeUpload"
            :on-change="handleFileChange"
            :file-list="fileList"
            :auto-upload="false"
            action="#"
            drag
          >
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">将文件拖到此处,或<em>点击上传</em></div>
          </el-upload>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="visible = false">取消</el-button>
        <el-button type="primary" @click="confirmImport" :loading="buttonLoading" :disabled="!fileRaw">
          开始比对
        </el-button>
      </div>
    </el-dialog>
  </MainCard>
</template>
  • 点击“新建比对”按钮,调用 openImportDialog 方法打开对话框。
  • 对话框中包含一个 el-upload 组件,用户可拖拽或点击上传文件。
脚本部分

对应的逻辑如下:

<script>
export default {
  data() {
    return {
      visible: false, // 控制对话框显示
      buttonLoading: false, // 按钮加载状态
      fileRaw: null, // 上传的原始文件
      fileList: [], // 文件列表
      limit: 1 // 限制上传一个文件
    };
  },
  methods: {
    // 打开导入对话框
    openImportDialog() {
      this.visible = true;
      this.$nextTick(() => {
        this.resetUpload(); // 重置上传状态
      });
    },
    // 重置上传组件
    resetUpload() {
      this.$refs['upload'].clearFiles();
      this.fileList = [];
      this.fileRaw = null;
    },
    // 文件移除时更新状态
    handleRemove(file, fileList) {
      this.fileList = fileList;
      if (fileList.length === 0) this.fileRaw = null;
    },
    // 文件选择时更新状态
    handleFileChange(file, fileList) {
      this.fileRaw = file.raw;
      this.fileList = fileList;
    },
    // 文件上传前校验
    handleBeforeUpload(file) {
      if (!this.validFile(file)) {
        return false;
      }
      this.fileRaw = file;
      this.fileList = [file];
      return false; // 阻止自动上传
    },
    // 文件校验逻辑
    validFile(file) {
      let fileName = file.name;
      const isLt10M = file.size / 1024 / 1024 < 10;
      const fitNameArr = ['xls', 'xlsx'];
      const index = fileName.lastIndexOf('.');
      if (index !== -1) {
        const suffName = fileName.slice(index + 1);
        if (!isLt10M) {
          this.$message({ message: '上传文件大小不能超过 10MB!', type: 'warning' });
          this.fileList = [];
          return false;
        }
        if (!fitNameArr.includes(suffName)) {
          this.$message.warning('只能上传xls或者xlsx格式的文件');
          this.fileList = [];
          return false;
        }
      } else {
        this.$message.warning('文件名称不合法');
        this.fileList = [];
        return false;
      }
      return true;
    }
  }
};
</script>
  • openImportDialog 打开对话框并重置上传状态。
  • handleBeforeUpload 校验文件大小(<10MB)和格式(xls/xlsx)。
  • handleFileChange 更新 fileRaw,用于后续比对。

2. 开始比对

点击“开始比对”按钮后,上传文件并调用后端接口。

模板部分

对话框底部已包含“开始比对”按钮,绑定 confirmImport 方法。

脚本部分

添加比对逻辑:

<script>
import { compareData } from '@/api/asset/assetReport/datacomparison';

export default {
  data() {
    return {
      visible: false,
      buttonLoading: false,
      fileRaw: null,
      fileList: [],
      limit: 1
    };
  },
  methods: {
    // 打开导入对话框(同上,略)
    // 文件相关方法(同上,略)

    // 开始比对
    async confirmImport() {
      if (!this.fileRaw) {
        this.$message.warning('请先选择需要比对的文档');
        return;
      }

      this.buttonLoading = true;
      const formData = new FormData();
      formData.append('file', this.fileRaw);

      try {
        const response = await compareData(formData);
        this.$message.success('比对完成');
      } catch (error) {
        this.$message.error('比对失败');
      } finally {
        this.buttonLoading = false;
        this.visible = false;
      }
    }
  }
};
</script>
  • 检查是否选择了文件,未选择则提示用户。
  • 使用 FormData 封装文件,调用 compareData 接口进行比对。
  • 根据结果显示成功或失败提示,并关闭对话框。

三、样式优化

为对话框添加简洁样式,提升用户体验:

<style lang="scss" scoped>
.mg20 {
  margin-bottom: 10px;
}

.importDialogBody {
  font-size: 13px;
  color: #606266;

  .title {
    font-weight: bold;
    margin-bottom: 10px;
    font-size: 16px;
    padding-left: 8px;
    position: relative;
  }

  .title::before {
    position: absolute;
    left: 0;
    top: 52%;
    transform: translateY(-50%);
    content: '';
    width: 4px;
    border-radius: 2px;
    background: #3d63c8;
    height: 90%;
  }

  .text-box {
    display: flex;
    flex-direction: column;
    align-items: center;
  }
}
</style>
  • .mg20 为按钮添加底部间距。
  • .importDialogBody 美化上传区域,标题前添加蓝色标识线。

四、总结

通过以上代码,我们实现了“新建比对”和“开始比对”的核心功能:

  • 点击“新建比对”打开上传对话框,支持文件校验。
  • 点击“开始比对”上传文件并调用后端接口,完成数据比对。

网站公告

今日签到

点亮在社区的每一天
去签到