- 資訊首頁(yè) > 開(kāi)發(fā)技術(shù) > web開(kāi)發(fā) > JavaScript >
- vue3+el-table實(shí)現行列轉換
為啥會(huì )出現行列轉換的問(wèn)題呢?因為用戶(hù)想看的是一張多列的大表單,但是數據庫里面保存的是“單列”的數據。于是就需要做一個(gè)轉換,這樣客戶(hù)看得更方便清晰。
SQL有一種寫(xiě)法可以支持這種行列轉換,但是寫(xiě)起來(lái)比如繞,不便于理解。
所以我個(gè)人還是傾向于在前端實(shí)現轉換的操作,因為可以節省后端的性能資源。
這里以成績(jì)單為例演示一下具體的實(shí)現方式。
這個(gè)又愛(ài)又恨的東東想必大家都不會(huì )陌生,這是一個(gè)比較典型的需要行列轉換的情景。
先回顧一下成績(jì)單的樣子:(圖片來(lái)自于網(wǎng)絡(luò ),侵刪)
成績(jì)單
分析一下,可以得到如下幾個(gè)基本元素:
元素的分類(lèi):
我們再看看數據庫里的設計,一般會(huì )設計幾個(gè)基礎表和一個(gè)成績(jì)表。
篇幅有限,具體字段就不介紹了,說(shuō)全的話(huà)也是挺復雜的。
行列轉換后的成績(jì)單
學(xué)科、學(xué)生、總分、平均分、最高分、最低分、名次都有了。還可以各種排序。下面我們來(lái)看看是如何實(shí)現的。
我們在前端模擬一下數據。(簡(jiǎn)化模式)
// 學(xué)科 —— 確定列 const subject = [ { id: 1, name: '數學(xué)' }, { id: 2, name: '語(yǔ)文' }, { id: 3, name: '物理' }, { id: 4, name: '化學(xué)' } ] // 學(xué)生 —— 確定行 const student = [ { id: 1, name: '張三' }, { id: 2, name: '李四' }, { id: 3, name: '王五' }, { id: 4, name: '趙六' } ] // 班級 —— 分類(lèi)依據 const classes = [ { id: 1, name: '一年一班' }, { id: 2, name: '一年二班' } ] // 考試 —— 分類(lèi)依據 const exam = [ { id: 1, name: '期中考試' }, { id: 2, name: '期末考試' } ] // 成績(jì) —— 確定內容 const reportCard = [ // 序號 考試ID 班級ID 學(xué)生ID 科目ID 成績(jì) { id: 1, examId: 1, classId: 1, studentId: 1, subjectId: 1, score: 100 }, { id: 2, examId: 1, classId: 1, studentId: 1, subjectId: 2, score: 98 }, { id: 3, examId: 1, classId: 1, studentId: 1, subjectId: 3, score: 90 }, { id: 4, examId: 1, classId: 1, studentId: 2, subjectId: 1, score: 90 }, { id: 5, examId: 1, classId: 1, studentId: 2, subjectId: 2, score: 90 }, { id: 6, examId: 1, classId: 1, studentId: 2, subjectId: 3, score: 40 }, { id: 7, examId: 1, classId: 1, studentId: 3, subjectId: 1, score: 30 }, { id: 8, examId: 1, classId: 1, studentId: 3, subjectId: 2, score: 90 }, { id: 8, examId: 1, classId: 1, studentId: 3, subjectId: 3, score: 40 }, { id: 9, examId: 1, classId: 1, studentId: 4, subjectId: 1, score: 64 }, { id: 8, examId: 1, classId: 1, studentId: 4, subjectId: 2, score: 90 }, { id: 9, examId: 1, classId: 1, studentId: 4, subjectId: 3, score: 70 } ]
element-plus 提供了一個(gè)很強大的 表格組件 —— el-table,可以實(shí)現很多基礎功能,比如排序、調整寬度、設置顏色、篩選等功能。那么我們可以使用這個(gè)組件來(lái)實(shí)現成績(jì)單。
行列轉換的一大特點(diǎn)是,表頭(有多少列)并不是固定的,而是需要動(dòng)態(tài)生成的。
以成績(jì)單為例,表頭列數由學(xué)科決定,學(xué)科越多,表頭也就越多。
首先我們按照 el-table 的要求設置一下表頭:
/** * 根據學(xué)科建立表頭 * * 學(xué)號、姓名、【各個(gè)學(xué)科】、總分、平均分、名次 */ const createTableHead = () => { // 添加學(xué)生 const head = [ { prop: 'id', label: '學(xué)號', width: 120 }, { prop: 'name', label: '姓名', width: 120 }] // 添加科目 for (const key in subject) { const sub = subject[key] head.push({ prop: 'sub_' + sub.id, label: sub.name, width: 120 }) } head.push({ prop: 'totalScore', label: '總分', width: 120 }) head.push({ prop: 'averageScore', label: '平均分', width: 120 }) head.push({ prop: 'ranking', label: '名次', width: 120 }) return head }
這里表頭分為兩種,一個(gè)是固定的,一個(gè)是根據科目動(dòng)態(tài)生成的。
我們采用簡(jiǎn)單粗暴的方式,先直接添加固定列,然后遍歷學(xué)科添加動(dòng)態(tài)列。
表頭確定好了之后,我們需要確定一下 data 部分,正式開(kāi)始行列轉換。
還是按照 el-table 的需要來(lái)定義一下數據格式:
{ id: 1, name: '張三', sub_1: 100, sub_2: 100, ... totalScore: 200, averageScore: 100, ranking: 1 }
中間可以有各個(gè)學(xué)科,屬性命名規則: 前綴 “sub_” + 學(xué)科ID 。
這樣便于后續添加數據。
遍歷成績(jì)表來(lái)填充數據。
/** * 行列轉換 */ const rowToCol = () => { // 對象形式的成績(jì)列表 const _code = {} // 數組形式的成績(jì)列表 const _arr = [] // 遍歷成績(jì)單 for (const key in reportCard) { const rep = reportCard[key] if(typeof _code[rep.studentId] === 'undefined') { // 沒(méi)有記錄。創(chuàng )建一行學(xué)生成績(jì),加入固定列的數據 _code[rep.studentId] = { id: rep.studentId, // 學(xué)生ID name: (student.filter((item)=>item.id === rep.studentId)[0] || {name:''}).name, // 根據id獲取學(xué)生姓名 totalScore: 0, // 學(xué)生的各科總分,后續修改 averageScore: 0, // 學(xué)生各科的平均分,后續修改 ranking: 1 // 名次,后續修改 } } // 記錄各科分數 _code[rep.studentId]['sub_' + rep.subjectId] = rep.score } // 計算總分、平均分 下面介紹 // 計算名次 下面介紹 return _arr }
遍歷成績(jì)單的數據,先依據學(xué)生ID建立一個(gè)對象,然后根據學(xué)科確定各科成績(jì)。
一般成績(jì)單還需要得到學(xué)生的總分和平均分,我們可以遍歷成績(jì)統計總分和平均分。
... // 計算總分、平均分 for(const key in _code) { const code = _code[key] // 遍歷學(xué)科 let total = 0 let ave = 0 let count = 0 for (const key in subject) { const fenshu = code['sub_' + subject[key].id] if (typeof fenshu !== 'undefined') { // 有成績(jì),計算總分和平均分 count++ total += fenshu ave = Math.floor(total / count * 10) / 10 // 保留一位小數。 // 如果保留兩位小數的話(huà)可以這樣 (total / count ).toFixed(2) } } code.totalScore = total code.averageScore = ave // 對象的數據轉為數組的數據 _arr.push(code) }
成績(jì)單有了,我們還需要做一個(gè)排名。
如果不需要排名次的話(huà),可以跳過(guò)此步驟。
let _ranking = 0 _arr.sort((a, b) => { // 按照總分倒序 return b.totalScore - a.totalScore }).forEach((item) => { // 設置名次 _ranking++ _arr.find((a) => a.id === item.id).ranking = _ranking })
這個(gè)也是比較常見(jiàn)的需求。
el-table 提供了自動(dòng)求和的功能,同時(shí)也提供了自定義求和的方法,我們可以利用他來(lái)實(shí)現學(xué)科的平均分。
下面是官網(wǎng)給出的方法,本來(lái)是求和的,稍微修改一下就可以得到學(xué)科的平均分。
// 計算各學(xué)科的平均分 let i = 0 const getSummaries = (param) => { i++ if (i < 7) return [] const { columns, data } = param; const sums = []; columns.forEach((column, index) => { if (index === 0) { sums[index] = '平均分' return } const values = data.map(item => Number(item[column.property])); if (!values.every(value => isNaN(value))) { sums[index] = values.reduce((prev, curr) => { const value = Number(curr) if (!isNaN(value)) { return prev + curr } else { return prev } }, 0); sums[index] = Math.floor(sums[index] / values.length * 10) / 10 } else { sums[index] = 'N/A'; } }) return sums
跟蹤了一下,發(fā)現這個(gè)函數會(huì )被調用七次,這個(gè)次數似乎和行數、列數沒(méi)有關(guān)系。
而且前幾次的 return 沒(méi)啥作用,最后一次才會(huì )有效,所以加了一個(gè)判斷。
一張成績(jì)單還可以計算各種數據,比如看看學(xué)科的最高分數、最低分數。
一般也可以關(guān)注一下這些統計數據,同樣我么可以用自定義求和的方法來(lái)實(shí)現需求,我么改進(jìn)一下 getSummaries。
// 計算各科目的平均分、最高分和最低分 const getSummaries = ({ columns }) => { i++ if (i < 7) return [] const sums = []; columns.forEach((item, index) => { if (item.property.indexOf('sub_') >= 0 ){ const subjectId = item.property.replace('sub_', '')*1 // 學(xué)科,計算平均值 let ave = 0 let sum = 0 let max = 0 let min = 99999 const _arr = reportCard.filter((r) => r.subjectId === subjectId) _arr.forEach((item, index) => { sum += item.score // 求和 if (max < item.score) max = item.score // 記錄最高分 if (min > item.score) min = item.score // 記錄最低分 }) if (_arr.length === 0) { sums[index] = '-' // 沒(méi)有成績(jì) } else { // 計算平均分 ave = Math.floor(sum/_arr.length * 10) / 10 sums[index] = `${ave}(${max}-${min})` } } else { // 不計算 sums[index] = '' } }) sums[0] = '統計' return sums }
這次我么直接同 reportCard 來(lái)統計平均分、最高分和最低分。
同理,我么還可以統計一下及格人數、各個(gè)分段的人數。
這個(gè)是 el-table 自帶的功能,我們加上就好。
<el-table :data="tableData" style="width: 100%;height: 300px;" :default-sort = "{prop: 'totalScore', order: 'descending'}" :row-class-name="tableRowClassName" border show-summary :summary-method="getSummaries" > <el-table-column v-for="(item, index) in tableHead" :key="'s'+ index" fixed sortable :prop="item.prop" :label="item.label" :width="item.width"> </el-table-column> </el-table>
el-table 的屬性設置。default-sort 默認按照 總分倒序顯示。
如果想要把平均分低于60的著(zhù)重表示出來(lái)怎么辦?el-table 也提供了功能,我們做一下判斷設置css即可。
// 顏色 const tableRowClassName = ({row, rowIndex}) => { if (row.averageScore < 60) { // 平均分不及格的同學(xué) return 'warning-row'; } else if (row.averageScore > 95) { // 平均分超過(guò)95的同學(xué) return 'success-row'; } return ''; }
源碼
小結
優(yōu)點(diǎn):
缺點(diǎn):
到此這篇關(guān)于vue3+el-table實(shí)現行列轉換的文章就介紹到這了,更多相關(guān)vue3 行列轉換內容請搜索腳本之家以前的文章或繼續瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng )、來(lái)自本網(wǎng)站內容采集于網(wǎng)絡(luò )互聯(lián)網(wǎng)轉載等其它媒體和分享為主,內容觀(guān)點(diǎn)不代表本網(wǎng)站立場(chǎng),如侵犯了原作者的版權,請告知一經(jīng)查實(shí),將立刻刪除涉嫌侵權內容,聯(lián)系我們QQ:712375056,同時(shí)歡迎投稿傳遞力量。
Copyright ? 2009-2022 56dr.com. All Rights Reserved. 特網(wǎng)科技 特網(wǎng)云 版權所有 特網(wǎng)科技 粵ICP備16109289號
域名注冊服務(wù)機構:阿里云計算有限公司(萬(wàn)網(wǎng)) 域名服務(wù)機構:煙臺帝思普網(wǎng)絡(luò )科技有限公司(DNSPod) CDN服務(wù):阿里云計算有限公司 百度云 中國互聯(lián)網(wǎng)舉報中心 增值電信業(yè)務(wù)經(jīng)營(yíng)許可證B2
建議您使用Chrome、Firefox、Edge、IE10及以上版本和360等主流瀏覽器瀏覽本網(wǎng)站