Vue 表格选择组件:鼠标自由选择 M 行 N 列表格
<p>"<template>\n <div class="table-selection-panel">\n <div class="table-title">\n <span class="table-select">{{ tableTitle }}</span>\n <span>表格</span>\n </div>\n <div class="table-panel" @mousemove="handleMouseMove" @mouseleave="handleMouseLeave" @click="handleClick">\n <table>\n <tr v-for="(row, rowIndex) in tableElementList" :key="rowIndex" class="table-row">\n <td v-for="(col, colIndex) in row" :key="colIndex" :class="{ 'table-col': true, 'active': colIndex < colIndex && rowIndex < rowIndex }"></td>\n </tr>\n </table>\n </div>\n </div>\n</template>\n\n<script>\nimport { ref } from 'vue';\n\nexport default {\n setup() {\n const tableTitle = ref('插入');\n const tableElementList = ref([]);\n const colIndex = ref(0);\n const rowIndex = ref(0);\n\n const drawTable = () => {\n for (let i = 0; i < 10; i++) {\n const trCellList = [];\n for (let j = 0; j < 10; j++) {\n trCellList.push({});\n }\n tableElementList.value.push(trCellList);\n }\n };\n\n const removeAllTableCellSelect = () => {\n tableElementList.value.forEach((tr) => {\n tr.forEach((td) => (td.active = false));\n });\n };\n\n const setTableTitleSelect = (payload) => {\n tableTitle.value = payload;\n };\n\n const recoveryTable = () => {\n removeAllTableCellSelect();\n setTableTitleSelect('插入');\n colIndex.value = 0;\n rowIndex.value = 0;\n };\n\n const handleMouseMove = (evt) => {\n const celSize = 16;\n const rowMarginTop = 10;\n const celMarginRight = 6;\n const { offsetX, offsetY } = evt;\n removeAllTableCellSelect();\n colIndex.value = Math.ceil(offsetX / (celSize + celMarginRight)) || 1;\n rowIndex.value = Math.ceil(offsetY / (celSize + rowMarginTop)) || 1;\n tableElementList.value.forEach((tr, trIndex) => {\n tr.forEach((td, tdIndex) => {\n if (tdIndex < colIndex.value && trIndex < rowIndex.value) {\n td.active = true;\n }\n });\n });\n setTableTitleSelect(<code>${rowIndex.value}×${colIndex.value}</code>);\n };\n\n const handleMouseLeave = () => {\n recoveryTable();\n };\n\n const handleClick = () => {\n // 假设 openAPI 和 getTableAPI 已经定义\n openAPI.getTableAPI().insertTable(Number(rowIndex.value), Number(colIndex.value));\n recoveryTable();\n };\n\n drawTable();\n\n return {\n tableTitle,\n tableElementList,\n colIndex,\n rowIndex,\n handleMouseMove,\n handleMouseLeave,\n handleClick\n };\n }\n};\n</script>\n\n<style>\n.table-selection-panel {\n display: block;\n}\n\n.table-title {\n display: flex;\n align-items: center;\n}\n\n.table-title .table-select {\n margin-right: 5px;\n}\n\n.table-panel {\n display: block;\n margin-top: 10px;\n}\n\n.table-panel table {\n border-collapse: collapse;\n}\n\n.table-panel .table-row {\n height: 16px;\n}\n\n.table-panel .table-col {\n width: 16px;\n border: 1px solid #000;\n}\n\n.table-panel .table-col.active {\n background-color: #ccc;\n}\n</style>\n</p>
原文地址: https://www.cveoy.top/t/topic/pV3K 著作权归作者所有。请勿转载和采集!