image.png
彈框組件(完整代碼)
<template>
<div>
<el-dialog title="導(dǎo)入excel" v-if="dialogVisible" :visible.sync="dialogVisible" width="40%">
<el-upload
class="ml-10"
:limit="limitNum"
:auto-upload="false"
accept=".xlsx"
:action="UploadUrl()"
:before-upload="beforeUploadFile"
:on-change="fileChange"
:on-exceed="exceedFile"
:on-success="handleSuccess"
:on-error="handleError"
:file-list="fileList"
>
<el-button slot="trigger" size="small" type="primary">導(dǎo)入資產(chǎn)</el-button>
<!-- <div class="el-upload__text">將文件拖到此處池颈,或<em>點擊上傳</em></div> -->
<div class="el-upload__tip" slot="tip">只能上傳xlsx文件,且不超過10M</div>
</el-upload>
<span slot="footer" class="dialog-footer">
<el-button @click="dialogVisible = false">取 消</el-button>
<el-button type="primary" @click="uploadFile">確 定</el-button>
</span>
</el-dialog>
</div>
</template>
<script>
export default {
data() {
return {
limitNum: 1, // 上傳excell時钓丰,同時允許上傳的最大數(shù)
fileList: [], // excel文件列表
dialogVisible: false,
};
},
methods: {
UploadUrl() {
// 因為action參數(shù)是必填項躯砰,我們使用二次確認(rèn)進(jìn)行文件上傳時,直接填上傳文件的url會因為沒有參數(shù)導(dǎo)致api報404携丁,所以這里將action設(shè)置為一個返回為空的方法就行琢歇,避免拋錯
return "";
},
// 文件超出個數(shù)限制時的鉤子
exceedFile(files, fileList) {
this.$message.warning(
`只能選擇 ${this.limitNum} 個文件,當(dāng)前共選擇了 ${files.length +
fileList.length} 個`
);
},
// 文件狀態(tài)改變時的鉤子
fileChange(file, fileList) {
console.log(file.raw);
this.fileList.push(file.raw);
console.log(this.fileList);
},
// 上傳文件之前的鉤子, 參數(shù)為上傳的文件,若返回 false 或者返回 Promise 且被 reject梦鉴,則停止上傳
beforeUploadFile(file) {
console.log("before upload");
console.log(file);
let extension = file.name.substring(file.name.lastIndexOf(".") + 1);
let size = file.size / 1024 / 1024;
if (extension !== "xlsx") {
this.$message.warning("只能上傳后綴是.xlsx的文件");
}
if (size > 10) {
this.$message.warning("文件大小不得超過10M");
}
},
// 文件上傳成功時的鉤子
handleSuccess(res, file, fileList) {
this.$message.success("文件上傳成功");
},
// 文件上傳失敗時的鉤子
handleError(err, file, fileList) {
this.$message.error("文件上傳失敗");
},
uploadFile() {
if (this.fileList.length === 0) {
this.$message.warning("請上傳文件");
} else {
let form = new FormData();
form.append("file", this.fileList[0]);
this.$emit('uploadFile',form)
this.fileList = [];
}
}
}
};
</script>
<style scoped>
</style>
封裝的請求
import axios from 'axios'
// 導(dǎo)入表格
export const uploadXlsx= (url,data)=>{
return axios({
method: "post",
url: `${url}`,
headers: {
"Content-type": "multipart/form-data"
},
data: data
})
}
main.js引用
import { uploadXlsx } from "./utils/api";
Vue.prototype.uploadXlsx = uploadXlsx;
頁面
import imporExcel from './imporExcel';//先引入組件(組件跟頁面同級目錄)
<el-button type="warning" size="small" @click="imporRuItem">導(dǎo)入資產(chǎn)</el-button>//導(dǎo)入按鈕點擊出現(xiàn)彈框
// 導(dǎo)入
imporRuItem(){
this.dialogVisible=true
this.$nextTick(() => {
this.$refs["dialogCom"].dialogVisible = true;
});
},
// 發(fā)送請求
uploadFile(form) {
this.uploadXlsx('/property/insertProperty',form).then(res=>{
this.dialogVisible=false
this.fetchData()//重新獲取自己表格列表的數(shù)據(jù)
})
},
完整寫下來就跟上面一樣的效果了