<template>
<div style="display: inline-block;">
<label for="excel-file" style="position: relative;display: inline-block;overflow: hidden;vertical-align: middle;"><input type="file" id="excel-file" :accept="accept" @change="getFile" style="position: absolute;top: 0; bottom: 0;right: 0;left: 0;opacity: 0;"><Button type="primary">导入</Button></label>
<Modal
v-model="progressShow"
title="导入进度"
footer-hide
:mask-closable="false"
width="300">
<Row>
<Col :span="4">进度</Col>
<Col :span="18"><Progress :percent="percent" :stroke-width="20" text-inside /></Col>
</Row>
<p style="text-align: center;">
当前已成功上传<b style="color: green;">{{liLen}}</b>条,共<b>{{ imCount }}</b>条<br>
上传失败<b style="color: red;">{{errCount}}</b>条
</p>
</Modal>
</div>
</template>
<script>
import { trim } from '@/components/view/libs/validate.js';
// require('script-loader!xlsx-style/dist/xlsx.full.min')
export default {
props: {
accept: { // 接受的导入的文件格式
type: String,
default: ''
},
postUrl: { // 提交的地址
type: String,
default: ''
},
otherOpt: { // 除导入数据外的其它配置参数
type: Object,
default: () => {
return {}
}
}
},
data(){
return {
progressShow: false,
percent: 0,
liLen: 0,
imCount: 0,
errCount: 0
}
},
mounted() {
},
methods: {
getFile(el) {
let _this = this;
var files = el.target.files;
var fileReader = new FileReader()
fileReader.readAsText(files[0],'utf8') // input.files[0]为第一个文件
fileReader.onload = function(e) {
el.target.value = ''
let result = JSON.parse(e.target.result)
console.log(result)
let cfgArr = []
let cfgVal = []
let cfgObj = {}
for(let key in result) {
if(result[key] instanceof Array) {
cfgVal.push(result[key])
}else if(typeof result[key] == 'object'){
cfgArr.push(result[key])
}else {
cfgObj[key] = result[key]
}
}
this.progressShow = true;
// for(let item of cfgArr) {
cfgArr.map((item, index) => {
let cfgArrObj = {}
for(let key in item) {
if(item[key] instanceof Array) {
cfgVal.push(item[key])
}else {
cfgArrObj[key] = item[key]
}
}
_this.imCount ++
_this.toImportAjax(cfgArrObj, index)
})
// for(let item of cfgVal) {
cfgVal.map((item, index) => {
// for(let dat of item) {
item.map((dat,i) => {
_this.imCount++
_this.toImportAjax(dat, i)
})
})
el.target.value = ''
}
},
dataToPostStr(dat) {
let str = ''
for(let key in dat) {
str+=key +'=' + dat[key] + '&'
}
return str.slice(0, -1)
},
toImportAjax(item) {
this.$ajax.post(this.postUrl, {...this.otherOpt, ...item}).then(res => {
if(res.data.code == 1) {
this.errCount ++
}else {
this.liLen ++
this.percent = (((this.liLen + this.errCount) / this.imCount) * 100).toFixed(2)
if((this.liLen + this.errCount) >= this.imCount) {
setTimeout(() => {
this.progressShow = false
this.liLen = 0;
this.errCount = 0;
this.imCount = 0;
this.percent = 0;
}, 3000)
}
}
}).catch(err => {
this.errCount ++
})
}
}
}
</script>
使用:
<importJsonBtn postUrl="/action/host_act" :otherOpt="otherOpt"></importJsonBtn>
引入与注册
//引入
import importJsonBtn from './importJsonBtn.vue'
//注册
export default {
components: importJsonBtn,
data() {
return {
otherOpt: {}
}
}
}