62、项目中常见的 Vue请求SpringBoot后端服务

一、查询后端数据到前端列表展示

1、后端的编写

  @ApiOperation(value = "查询列表")
    @PostMapping(value = "/list")
    public RespPageBean list(@RequestBody PersonVo personVo) {
        RespPageBean result = peronService.getList(personVo);
        return result;
    }
 /**
     * 使用MybatisPlus的条件构造器查询,并进行分页
     */
    public RespPageBean getList(PersonVo personVo) {
        QueryWrapper<Person> queryWrapper = new QueryWrapper<>();
        if (Util.isNotEmpty(personVo.getNameZh())) {
            queryWrapper.like("nameZh", personVo.getNameZh());
        }
        if (Util.isNotEmpty(personVo.getNameEn())) {
            queryWrapper.like("nameEn", personVo.getNameEn());
        }
        if (Util.isNotEmpty(personVo.getPhone())) {
            queryWrapper.like("phone", personVo.getPhone());
        }
        if (Util.isNotEmpty(personVo.getXueLi())) {
            queryWrapper.like("xueLi", personVo.getXueLi());
        }
        Page<Person> page = new Page<>(personVo.getPageNum(), personVo.getPageSize());
        Page<Person> personPage = personMapper.selectPage(page, queryWrapper);
        RespPageBean respPageBean = new RespPageBean(personPage.getTotal(), personPage.getRecords());
        return respPageBean;
    }

2、前端写法

//传送json格式的post请求
export const postRequest = (url, params) => {
  return axios({
    method: 'post',
    url: `${base}${url}`,
    data: params
  })
}
initPersons() {
        this.postRequest('/person/list', this.personForm).then(resp => {
          if (resp) {
            this.personList = resp.data;
            this.totalSize = resp.total;
          }
        })
      },

二、删除方法

1、后台的写法

    @ApiOperation(value = "删除人员/支持批量删除")
    @DeleteMapping("/delete")
    private RespBean deletePerson(@RequestParam(name = "ids") Long[] ids) {
        Integer success = peronService.deletePerson(ids);
        return success > 0 ? RespBean.success("删除成功!") : RespBean.error("删除失败!");
    }

2、前端写法

//单条删除
deletePerson(index, data) {
        this.$confirm('此操作将永久删除【' + data.nameZh + '】记录, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          let ids = '?';
          ids += 'ids=' + data.id + '&';
          this.deleteRequest('/person/delete' + ids).then(resp => {
            if (resp) {
              this.initPersons();
            }
          });
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
      },
//批量删除
bathDelete() {
        this.$confirm('此操作将永久删除【' + this.multipleSelection.length
          + '】条记录, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          let ids = '?';
          this.multipleSelection.forEach(item => {
            ids += 'ids=' + item.id + '&';
          });
          this.deleteRequest('/person/delete' + ids).then(resp => {
            if (resp) {
              this.initPersons();
            }
          });
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
      },

三、导出excel表格

1、后端的写法

    @ApiOperation(value = "导出")
    @PostMapping(value = "/export")
    public void export(@RequestBody PersonVo personVo, HttpServletResponse response) throws IOException {
        long begin = System.currentTimeMillis();
        List<PersonExport> exportList = peronService.export(personVo);
        log.info("导出加减表获取数据耗时{}ms", System.currentTimeMillis() - begin);
        new EasyExcelUtils().writeToResponse(response, "人员列表", "人员列表", PersonExport.class, exportList);
        log.info("导出加减表数据总耗时{}ms", System.currentTimeMillis() - begin);
    }

2、前端写法

exportData() {
        var _this = this;
        this.axios({
          method: "post", url: '/person/export', data: _this.personForm, responseType: 'blob',
          headers: {
            Authorization: window.sessionStorage.getItem('tokenStr'),
            "Content-Type": "application/json"
          },
        }).then(function (res) {
          let fileName = '人员信息列表.xls';
          let blob = new Blob([res], {type: 'application/x-xls'});
          if (window.navigator.msSaveOrOpenBlob) {
            navigator.msSaveBlob(blob, fileName);
          } else {
            var link = document.createElement('a');
            link.href = window.URL.createObjectURL(blob);
            link.download = fileName;
            link.click();
            window.URL.revokeObjectURL(link.href);
          }
        }).catch(function (res) {
          _this.$message({
            message: res.data.message,
            type: "warning"
          });
        });
      },

四、上传文件

1、后端的写法

    @ApiOperation(value = "新增附件")
    @PostMapping(value = "/saveAttachment")
    public RespBean saveAttachment(@RequestPart MultipartFile file) {
        Attachment attachment = peronService.saveAttachment(file);
        return RespBean.success("新增成功!", attachment);
    }
 public Attachment saveAttachment(MultipartFile file) {
        Admin user = (Admin) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        Attachment attachment = new Attachment();
        if (file == null) {
            throw new RuntimeException("上传的文件为空!");
        }
        try {
            attachment.setAttachmentName(file.getOriginalFilename());
            String fileType = file.getOriginalFilename().substring(file.getOriginalFilename().indexOf(".") + 1, file.getOriginalFilename().length());
            attachment.setType(fileType);
            attachment.setFileData(file.getBytes());
            attachment.setCreateBy(user.getName());
            attachmentMapper.insert(attachment);
        } catch (Exception e) {

        }
        return attachment;
    }

2、前端的写法

beforeUpload(file) {
        let thas = this;
        this.files = file;
        let formData = new FormData();
        formData.append("file", file);
        let config = {headers: {'Content-Type': 'multipart/form-data'}};
        this.axios.post('/person/saveAttachment', formData, config).then(resp => {
          if (resp) {
            setTimeout(function () {
              thas.person.attachmentId = resp.obj.id;
              thas.person.attachmentName = resp.obj.attachmentName;
              thas.isShow = false;
            }, 2000);
          }
        });
        return false;
      },

五、导入execl数据

1、后端下载导入模板写法

    @ApiOperation(value = "下载导入模板")
    @GetMapping("/downloadTemp")
    public void downLoadTemplate(@RequestParam("filePath") String filePath,HttpServletResponse response) {
        peronService.downLoadTemplate(filePath,response);
    }
public void downLoadTemplate(String filePath, HttpServletResponse response) {
        InputStream inputStream = ClassUtils.class.getClassLoader().getResourceAsStream(filePath);
        String fileName = "person_upload.xls";
        ServletOutputStream outputStream = null;
        try {
            //流形式
            response.setHeader("content-type","application/octet-stream");
            //中文乱码
            response.setHeader("content-disposition","attachment;filename="+ URLEncoder.encode(fileName,"UTF-8"));
            outputStream = response.getOutputStream();
            outputStream.write(IOUtils.toByteArray(inputStream));
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if (null != outputStream){
                try {
                    outputStream.flush();
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

2、前端写法

let base = '';
export const downloadRequest = (url, params) => {
  return service({
    method: 'get',
    url: `${base}${url}`,
    data: params
  })
}
 downLoadTemplate() {
        let filePath = 'templates/person_upload.xls';
        this.downloadRequest('/person/downloadTemp?filePath=' + filePath);
      },

3、导入数据 后端写法

    @ApiOperation(value = "解析导入的数据")
    @PostMapping(value = "/analysisData")
    public Map<String,Object> analysisData(@RequestParam(name = "file") MultipartFile file) {
        Map<String,Object> result = peronService.analysisData(file);
        return  result;
    }

4、前端写法

importBeforeUpload(file) {
        this.files = file;
        let formData = new FormData();
        formData.append('file', file);
        this.fileSize = 1;
        if (this.fileSize === 0) {
          this.$message.error('请先上传导入文件!');
          return;
        }
        this.postRequest('/person/analysisData', formData).then(resp => {
          if (resp) {
            this.$refs.upload.clearFiles();
            this.formData = null;
            this.fileSize = 0;
            //打开确认导入弹框
            this.failCount = resp.failCount;
            this.requestId = resp.requestId;
            this.dataList = resp.data;
            this.queRenDialogVisible = true;
          }
        });
        return true;
      },

 后端确定导入

    @ApiOperation(value = "确定导入")
    @GetMapping(value = "/upload")
    public RespBean upload(@RequestParam(name = "requestId") String requestId) {
        peronService.uploadPerson(requestId);
        return  RespBean.success("导入成功!");
    }

前端写法

applyImport() {
        console.info("redisKey===>", this.requestId);
        this.$confirm('该操作将导入校验成功的数据,是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.getRequest('/person/upload?requestId=' + this.requestId).then(resp => {
            if (resp) {
              this.$message.success('导入成功!');
              this.uploadDialogVisible = false;
              this.queRenDialogVisible = false;
              this.initPersons();
            }
          });
        }).catch(() => {
          this.$message({type: 'info', message: '已取消删除'});
        });
      },

 

posted @ 2021-10-31 22:25  shunnWcs  阅读(417)  评论(0)    收藏  举报