最佳实践
大约 1 分钟Fe basichtml
Grid布局实现自定义表格
GridTable
<!-- ↑ 你也可以使用 html -->
<template>
<!-- vue 模板 -->
<div id="app">
<main>
<div class="frame" :style="{ gridTemplateColumns: colFrs, gridTemplateRows: rowFrs }">
<template v-for="rows in tableData.cells">
<div class="cell" :class="{active: cell.active}" v-for="cell in rows" :style="{gridArea: cell.area.join(' / ')}" @click="showCell(cell)">
{{cell.coordinate[0]}}, {{ cell.coordinate[1]}}
</div>
</template>
<div class="cell new-cell" :class="{active: newArea.active}" v-for="newArea in combineAreas" :style="{gridArea: newArea.area.join(' / ')}"
@click="showCell(newArea)">
{{newArea.area}}
</div>
</div>
</main>
</div>
</template>
<script>
export default {
// vue 组件
data () {
return {
tableData: {
row: 4,
col: 9,
rowHeights: [100, 200, 200, 100],
cells: []
},
lastCell: null,
combineAreas: []
}
},
computed: {
total() {
return new Array(this.tableData.row * this.tableData.col);
},
rows() {
return new Array(this.tableData.row);
},
cols() {
return new Array(this.tableData.col);
},
colFrs() {
return `repeat(${this.cols.length}, 1fr)`;
},
rowFrs() {
return `repeat(${this.rows.length}, 1fr)`;
},
},
created() {
for(let i = 0 ; i< this.tableData.row; i++) {
let row = []
for(let j = 0; j < this.tableData.col; j++) {
row.push({coordinate: [i, j], area: [i+1, j+1, i+2, j+2], active: false})
}
this.tableData.cells.push(row)
}
this.combineAreas.push({
area: [1, 1, 3, 4],
active: false
})
},
methods: {
showCell(cell) {
if(this.lastCell) {
this.lastCell.active = false
}
cell.active = true
this.lastCell = cell
}
}
}
</script>
<style>
/* css 代码 */
* {
box-sizing: border-box;
}
body {
margin: 0;
font-family: system-ui, sans-serif;
color: black;
background-color: white;
}
nav {
display: flex;
flex-wrap: wrap;
align-items: center;
justify-content: center;
padding: 0.5rem;
gap: 0.5rem;
border-bottom: solid 1px #aaa;
background-color: #eee;
}
nav a {
display: inline-block;
min-width: 9rem;
padding: 0.5rem;
border-radius: 0.2rem;
border: solid 1px #aaa;
text-align: center;
text-decoration: none;
color: #555;
}
nav a[aria-current='page'] {
color: #000;
background-color: #d4d4d4;
}
main {
padding: 10px;
}
h1 {
font-weight: bold;
font-size: 1.5rem;
}
.frame {
display: grid;
grid-column-gap: 0px;
grid-row-gap: 0px;
border-top: 1px solid #ddd;
border-left: 1px solid #ddd;
}
.cell {
border-right: 1px solid #ddd;
border-bottom: 1px solid #ddd;
cursor: pointer;
}
.cell.active {
background: #eee;
}
.new-cell {
background: yellow;
}
</style>