Vue 表格选择组件:自由选择插入表格大小
<template>
<div class="table-selection-panel">
<div class="table-title">
<span class="table-select" ref="tableTitleSelect">插入</span>
<span>表格</span>
</div>
<div class="table-panel" @mousemove="onMouseMove" @mouseleave="recoveryTable" @click="insertTable">
<table>
<tbody>
<tr v-for="(row, rowIndex) in tableElementList" :key="rowIndex">
<td v-for="(cell, colIndex) in row" :key="colIndex" :class="{ 'active': isSelected(rowIndex, colIndex) }"></td>
</tr>
</tbody>
</table>
</div>
</div>
</template>
<script>
export default {
data() {
return {
tableElementList: [],
colIndex: 0,
rowIndex: 0
};
},
mounted() {
this.drawTable();
},
methods: {
drawTable() {
for (let i = 0; i < 10; i++) {
const tr = [];
for (let j = 0; j < 10; j++) {
tr.push({});
}
this.tableElementList.push(tr);
}
},
isSelected(rowIndex, colIndex) {
return rowIndex < this.rowIndex && colIndex < this.colIndex;
},
setTableTitleSelect(payload) {
this.$refs.tableTitleSelect.innerText = payload;
},
recoveryTable() {
this.colIndex = 0;
this.rowIndex = 0;
this.removeAllTableCellSelect();
this.setTableTitleSelect('插入');
},
insertTable(evt) {
this.openAPI.getTableAPI().insertTable(Number(this.rowIndex), Number(this.colIndex));
this.recoveryTable();
// evt.stopPropagation();
},
onMouseMove(evt) {
const celSize = 16;
const rowMarginTop = 10;
const celMarginRight = 6;
const { offsetX, offsetY } = evt;
this.removeAllTableCellSelect();
this.colIndex = Math.ceil(offsetX / (celSize + celMarginRight)) || 1;
this.rowIndex = Math.ceil(offsetY / (celSize + rowMarginTop)) || 1;
this.tableElementList.forEach((tr, trIndex) => {
tr.forEach((td, tdIndex) => {
if (tdIndex < this.colIndex && trIndex < this.rowIndex) {
this.$set(td, 'active', true);
}
});
});
this.setTableTitleSelect(`${this.rowIndex}×${this.colIndex}`);
},
removeAllTableCellSelect() {
this.tableElementList.forEach((tr) => {
tr.forEach((td) => {
this.$set(td, 'active', false);
});
});
}
}
};
</script>
<style scoped>
.table-selection-panel {
display: block;
}
.table-title {
display: flex;
justify-content: space-between;
margin-bottom: 10px;
}
.table-select {
font-weight: bold;
}
.table-panel table {
border-collapse: collapse;
}
.table-panel td {
width: 16px;
height: 16px;
border: 1px solid #ccc;
}
.table-panel td.active {
background-color: #ccc;
}
</style>
原文地址: https://www.cveoy.top/t/topic/pV3p 著作权归作者所有。请勿转载和采集!