riku
2024-11-04 069da66fbe2748d51b1f3bc63f9ae00e660083c6
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
import { ref, watch } from 'vue';
import { useEvent } from './event';
 
/**
 * 表格多行多列粘贴事件
 * @param {object} obj 需要粘贴的属性以及对应的列索引值,其中字段名为属性名,值为索引值
 * @returns
 */
export function useTablePaste(obj) {
  const { invokeEvent, addEvent: addRefreshEvent } = useEvent();
 
  const rowIndex = ref(0);
  const columnIndex = ref(0);
  const tableData = ref([]);
 
  function setTableData(data) {
    tableData.value = data;
  }
 
  function cellClick(row, column, cell, event) {
    rowIndex.value = row.index;
    columnIndex.value = column.index;
  }
  function cellClassName({ row, column, rowIndex, columnIndex }) {
    row.index = rowIndex;
    column.index = columnIndex;
  }
  function handlePaste(event) {
    // 阻止默认的粘贴行为和事件冒泡。
    event.preventDefault();
    event.stopPropagation();
 
    // 获取剪贴板数据并提取纯文本内容。
    const clipboardData = event.clipboardData;
    const text = clipboardData.getData('text/plain');
    // 将文本内容按行和制表符分割,转换为二维数组
    let pastedText = text.split('\n').map((row) => {
      return row.split('\t').map((ele) => {
        return parseFloat(ele);
      });
    });
    // 表格多行多列粘贴事件。
    // let obj = {
    //   score1: null,
    //   score2: null
    // };
    // 遍历处理每一行数据,根据行索引和列索引将数据填充到表格中。
    pastedText.forEach((ele1, index) => {
      if (rowIndex.value + index <= tableData.value.length - 1) {
        // let item = JSON.parse(JSON.stringify(tableData[rowIndex + index]));
        let item = tableData.value[rowIndex.value + index];
        let num = 0;
        // 使用循环和条件判断,将处理后的数据按列索引填充到克隆的行对象中
        for (let key in obj) {
          const value = obj[key];
          if (num < ele1.length && value >= columnIndex.value) {
            item[key] = ele1[num] || ele1[num] == 0 ? ele1[num] : null;
            num++;
          }
        }
      }
    });
    invokeEvent();
  }
 
  return { cellClick, cellClassName, handlePaste, setTableData, addRefreshEvent, tableData };
}