欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

vue + element-ui实现简洁的导入导出功能

程序员文章站 2022-08-09 13:29:26
前言 众所周知,elementui,是一个比较完善的ui库,但是使用它需要有一点vue的基础。在开始本文的正文之前,我们先来看看安装的方法吧。 安装elementui模...

前言

众所周知,elementui,是一个比较完善的ui库,但是使用它需要有一点vue的基础。在开始本文的正文之前,我们先来看看安装的方法吧。

安装elementui模块

cnpm install element-ui -s

在main.js中引入

import elementui from 'element-ui'
import 'element-ui/lib/theme-default/index.css'

全局安装

vue.use(elementui)

当我们安装完记得重新运行,cnpm run dev ,现在就可以直接使用elementui了。

vue + element-ui导入导出功能

1.前段后台管理系统中数据展示一般都是用表格,表格会涉及到导入和导出;

2.导入是利用element-ui的upload 上传组件;

<el-upload class="upload-demo"
  :action="importurl"//上传的路径
  :name ="name"//上传的文件字段名
  :headers="importheaders"//请求头格式
  :on-preview="handlepreview"//可以通过 file.response 拿到服务端返回数据
  :on-remove="handleremove"//文件移除
  :before-upload="beforeupload"//上传前配置
  :on-error="uploadfail"//上传错误
  :on-success="uploadsuccess"//上传成功
  :file-list="filelist"//上传的文件列表
  :with-credentials="withcredentials">//是否支持cookie信息发送
</el-upload>

3.导出是利用file的一个对象blob;通过调用后台接口拿到数据,然后用数据来实例化blob,利用a标签的href属性链接到blob对象

 export const downloadtemplate = function (scheduletype) {
  axios.get('/rest/schedule/template', {
   params: {
    "scheduletype": scheduletype
   },
   responsetype: 'arraybuffer'
  }).then((response) => {
   //创建一个blob对象,file的一种
   let blob = new blob([response.data], { type: 'application/x-xls' })
   let link = document.createelement('a')
   link.href = window.url.createobjecturl(blob)
   //配置下载的文件名
   link.download = filenames[scheduletype] + '_' + response.headers.datestr + '.xls'
   link.click()
  })
 }

4.贴上整个小demo的完整代码,在后台开发可以直接拿过去用(vue文件)

<template>
<div>
 <el-table
 ref="multipletable"
 :data="tabledata3"
 tooltip-effect="dark"
 border
 style="width: 80%"
 @selection-change="handleselectionchange">
 <el-table-column
  type="selection"
  width="55">
 </el-table-column>
 <el-table-column
  label="日期"
  width="120">
  <template slot-scope="scope">{{ scope.row.date }}</template>
 </el-table-column>
 <el-table-column
  prop="name"
  label="姓名"
  width="120">
 </el-table-column>
 <el-table-column
  prop="address"
  label="地址"
  show-overflow-tooltip>
 </el-table-column>
 </el-table>
 <div style="margin-top: 20px">
 <el-button @click="toggleselection([tabledata3[1], tabledata3[2]])">切换第二、第三行的选中状态</el-button>
 <el-button @click="toggleselection()">取消选择</el-button>
 <el-button type="primary" @click="importdata">导入</el-button>
 <el-button type="primary" @click="outportdata">导出</el-button>
 </div>
 <!-- 导入 -->
 <el-dialog title="导入" :visible.sync="dialogimportvisible" :modal-append-to-body="false" :close-on-click-modal="false" class="dialog-import">
  <div :class="{'import-content': importflag === 1, 'hide-dialog': importflag !== 1}">
  <el-upload class="upload-demo"
  :action="importurl"
  :name ="name"
  :headers="importheaders"
  :on-preview="handlepreview"
  :on-remove="handleremove"
  :before-upload="beforeupload"
  :on-error="uploadfail"
  :on-success="uploadsuccess"
  :file-list="filelist"
  :with-credentials="withcredentials">
  <!-- 是否支持发送cookie信息 -->
   <el-button size="small" type="primary" :disabled="processing">{{uploadtip}}</el-button>
   <div slot="tip" class="el-upload__tip">只能上传excel文件</div>
  </el-upload>
  <div class="download-template">
   <a class="btn-download" @click="download">
   <i class="icon-download"></i>下载模板</a>
  </div>
  </div>
  <div :class="{'import-failure': importflag === 2, 'hide-dialog': importflag !== 2}" >
  <div class="failure-tips">
   <i class="el-icon-warning"></i>导入失败</div>
  <div class="failure-reason">
   <h4>失败原因</h4>
   <ul>
   <li v-for="(error,index) in errorresults" :key="index">第{{error.rowidx + 1}}行,错误:{{error.column}},{{error.value}},{{error.errorinfo}}</li>
   </ul>
  </div>
  </div>
 </el-dialog>

 <!-- 导出 -->
</div>
</template>
<script>
import * as scheduleapi from '@/api/schedule'
export default {
 data() {
 return {
  tabledata3: [
  {
   date: "2016-05-03",
   name: "王小虎",
   address: "上海市普陀区金沙江路 1518 弄"
  },
  {
   date: "2016-05-02",
   name: "王小虎",
   address: "上海市普陀区金沙江路 1518 弄"
  },
  {
   date: "2016-05-04",
   name: "王小虎",
   address: "上海市普陀区金沙江路 1518 弄"
  },
  {
   date: "2016-05-01",
   name: "王小虎",
   address: "上海市普陀区金沙江路 1518 弄"
  },
  {
   date: "2016-05-08",
   name: "王小虎",
   address: "上海市普陀区金沙江路 1518 弄"
  },
  {
   date: "2016-05-06",
   name: "王小虎",
   address: "上海市普陀区金沙江路 1518 弄"
  },
  {
   date: "2016-05-07",
   name: "王小虎",
   address: "上海市普陀区金沙江路 1518 弄"
  }
  ],
  multipleselection: [],
  importurl:'www.baidu.com',//后台接口config.admin_url+'rest/schedule/import/'
  importheaders:{
  enctype:'multipart/form-data',
  citycode:''
  },
  name: 'import',
  filelist: [],
  withcredentials: true,
  processing: false,
  uploadtip:'点击上传',
  importflag:1,
  dialogimportvisible:false,
  errorresults:[]
 };
 },
 methods: {
 toggleselection(rows) {
  if (rows) {
  rows.foreach(row => {
   this.$refs.multipletable.togglerowselection(row);
  });
  } else {
  this.$refs.multipletable.clearselection();
  }
 },
 handleselectionchange(val) {
  //复选框选择回填函数,val返回一整行的数据
  this.multipleselection = val;
 },
 importdata() {
  this.importflag = 1
  this.filelist = []
  this.uploadtip = '点击上传'
  this.processing = false
  this.dialogimportvisible = true
 },
 outportdata() {
  scheduleapi.downloadtemplate()
 },
 handlepreview(file) {
  //可以通过 file.response 拿到服务端返回数据
 },
 handleremove(file, filelist) {
  //文件移除
 },
 beforeupload(file){
  //上传前配置
  this.importheaders.citycode='上海'//可以配置请求头
  let excelfileextend = ".xls,.xlsx"//设置文件格式
  let fileextend = file.name.substring(file.name.lastindexof('.')).tolowercase();
  if (excelfileextend.indexof(fileextend) <= -1) {
   this.$message.error('文件格式错误')
   return false
  }
  this.uploadtip = '正在处理中...'
  this.processing = true
 },
 //上传错误
 uploadfail(err, file, filelist) {
  this.uploadtip = '点击上传'
  this.processing = false
  this.$message.error(err)
 },
 //上传成功
 uploadsuccess(response, file, filelist) {
  this.uploadtip = '点击上传'
  this.processing = false
  if (response.status === -1) {
  this.errorresults = response.data
  if (this.errorresults) {
   this.importflag = 2
  } else {
   this.dialogimportvisible = false
   this.$message.error(response.errormsg)
  }
  } else {
  this.importflag = 3
  this.dialogimportvisible = false
  this.$message.info('导入成功')
  this.dosearch()
  }
 },
 //下载模板
 download() {
  //调用后台模板方法,和导出类似
  scheduleapi.downloadtemplate()
 },
 }
};
</script>
<style scoped>
.hide-dialog{
 display:none;
}
</style>

5.js文件,调用接口

import axios from 'axios'
// 下载模板
 export const downloadtemplate = function (scheduletype) {
  axios.get('/rest/schedule/template', {
   params: {
    "scheduletype": scheduletype
   },
   responsetype: 'arraybuffer'
  }).then((response) => {
   //创建一个blob对象,file的一种
   let blob = new blob([response.data], { type: 'application/x-xls' })
   let link = document.createelement('a')
   link.href = window.url.createobjecturl(blob)
   link.download = filenames[scheduletype] + '_' + response.headers.datestr + '.xls'
   link.click()
  })
 }

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对的支持。