import { getCurrentInstance, ref } from 'vue' import mitt from './bus' export default function () { const tempColOptions = ref([]) const elTableNode = ref(null) const selectionArr = ref([]) let lastAll = [] const { props } = getCurrentInstance() as any const key = props.selectionKey if (props.selection) { tempColOptions.value = [ { type: 'selection', width: '55' }, ...props.colOption, ] } else { tempColOptions.value = props.colOption } function include (arr, data) { return arr.filter(item => item[key] === data[key]).length > 0 } function addSelections(data) { if (!include(selectionArr.value, data)) selectionArr.value.push(data) } function subSelections(data) { if (include(selectionArr.value, data)) { let index = -1 for (let i = 0; i < selectionArr.value.length; i++) { if (selectionArr.value[i][key] === data.id) { index = i } } index !== -1 && selectionArr.value.splice(index, 1) } } const handleSelect = (selection, row) => { if (include(selection, row)) addSelections(row) else subSelections(row) } const handleSelectAll = selection => { if (selection.length > 0) { lastAll = selection selection.forEach(item => { handleSelect(selection, item) }) } else { lastAll.forEach(item => { subSelections(item) }) } } mitt.on('dataChange', value => { fillBack(value) }) function fillBack (value) { const length = value.length const tempArr = [] let index = 0 selectionArr.value.forEach(item => { value.forEach(ii => { if (item.id === ii.id) { index++ tempArr.push(ii) } }) }) if (length === index) lastAll = tempArr tempArr.forEach(item => { elTableNode.value.toggleRowSelection(item) }) } return { tempColOptions, elTableNode, handleSelect, handleSelectAll, } }