前提: 參考 潘大佬 的代碼, 別忘了下載中文分支的, 運行找到該頁面
父傳子 傳值
理解: 方法等寫在子組件, 父組件使用封裝的組件時候, 把表格數據傳給子組件. 使用的直接全貼了, 方便自己以后看
father代碼

// 導出excel表格 父組件 -- 主要看組件使用 和 組件傳值 <template> <div class="contentWrap purchaseMange"> <el-row class="handlePart"> <ul class="handleCont blod"> <!-- 導出按鈕組件使用 --> <exportExcel :exceltitle="excelTitle" :exceldata="excelData" :filterval="filterVal" :filename="fileName" /> <el-row> <el-table :data="tableData"> <el-table-column type="index" label="序號"></el-table-column> <!--循環渲染出來真的好用 如果這里面有操作項 可以if-else使用<template slot-scope="scope">{{ scope.row.}}</template>--> <el-table-column v-for="(item, index) in column" :label="item.title" :prop="item.key" :fixed="item.fixed" :minWidth="item.width ? item.width : 120" :key="index"></el-table-column> </el-table> </el-row> </ul> </div> </template> <script> // 引入子組件 import ExportExcel from "@/components/excel/exportExcel.vue"; export default { components: { ExportExcel // 注冊組件 }, data() { return { // 導出數據標題 excelTitle: [], // 導出數據內容 excelData: null, // 導出數據的參數值 為了filterVal filterVal: [], // 導出數據名稱 fileName: "", // 頁面表格數據 // 列數據 column: [ { title: "訂單編號", key: "cityNum", width: 120, fixed: "left"}, { title: "業務日期", key: "createTime", width: 120 }, ............ ] }; }, created() { // 初始化渲染數據 根據需要改動 this.handleGetlist(); }, methods: { // 獲取數據 handleGetlist (param) { // 走個ajax 成功開始 // 獲取到數據 this.excelData = res.data ; // 標題需要做循環處理 表格上面這樣寫更方便獲取標題和內容 this.column.forEach((element, index) => { // 導出數據內容 this.excelTitle.push(element.title); // 導出數據的參數值 為了filterVal this.filterVal.push(element.key); // 導出excel的表名 this.fileName = "根據需求自定義一個表"; }); // 走個ajax 成功結束 } }, }; </script>
child代碼

// 子組件 導出excel功能 <template> <li @click="hanleExport">導出</li> </template> <script> export default { props: [ // 導出數據標題 "exceltitle", // 導出數據內容 "exceldata", // 導出數據的參數值 為了filterVal "filterval", // 導出數據名稱 "filename" ], methods: { // 導出 hanleExport(data) { // 導出文件是 ‘業務日期起-業務日期止’采購訂單.xlsx” this.downloadLoading = true; import("@/vendor/Export2Excel").then(excel => { const excelData = this.exceldata; const filterVal = this.filterval; // 格式化數據 過濾並轉換所需要的數據 const data = this.formatJson(filterVal, excelData); excel.export_json_to_excel({ header: this.exceltitle, data, filename: this.filename }); this.downloadLoading = false; }); }, // 格式化數據 過濾並轉換 formatJson(filterVal, jsonData) { return jsonData.map(v => filterVal.map(j => { if (j === "timestamp") { return parseTime(v[j]); } else { return v[j]; } }) ); } } }; </script> <style></style>
注意:在引入這一個Export2Excel.js文件 會報錯 當時提示忘了截圖了, 大概意思是"npm install Export2Excel -g -find" ,讓你安裝, 給你啥命令提示, 就敲啥
按照vue-element-admin源碼引用excel的時候 vendor文件放置位置