vue3+element-plus列表复选框分页保持之前的选中状态

复选框事件分为选择多个(@select)和选择全部(@select-all)

//entity_id为每列数组的唯一标识

const handleSelect = (selection: any, row: any) => {

    let selectType = '';

    const filterList = selection.filter((item: any) => item.entity_id === row.entity_id);

    if (filterList.length > 0) selectType = 'add';

    else selectType = 'delete';



    if (selectType === 'add') {

        const cartFilterList = cart.filter((item) => item.entity_id === row.entity_id);

        if (cartFilterList.length === 0) {

            cart.push({ ...row, deleteable: true });

        }

    } else {

        const cartFilterList = cart

            .filter((item) => item.entity_id !== row.entity_id)

            .map((item) => {

                return { ...item, deleteable: true };

            });

        cart.length = 0;

        cart.push(...cartFilterList);

    }

};

const handleSelectAll = function (selection: any) {

    if (selection.length === 0) {

        const cartFilterList = cart

            .filter((item) => {

                return tableData.value.findIndex((row: any) => row.entity_id === item.entity_id) === -1;

            })

            .map((item) => {

                return { ...item, deleteable: true };

            });

        cart.length = 0;

        cart.push(...cartFilterList);

    } else {

        const selectionFilterList = selection

            .filter((row: any) => {

                return cart.findIndex((item) => item.entity_id === row.entity_id) === -1;

            })

            .map((item: any) => {

                return { ...item, deleteable: true };

            });

        cart.push(...selectionFilterList);

    }

};

注意:将接口获取到的数据直接赋值给tableData不会触发watch事件,需要将接口返回的数据做一次处理watch事件才会触发,

// 翻页时勾选状态保留 &重置清空勾选状态

const setSelectedCheckBox = function () {

    cart.forEach((item) => {

        const targetRow = tableData.value.find((row: any) => row.entity_id === item.entity_id);

        if (targetRow) {

            tableRef.value.toggleRowSelection(targetRow, true);

        }

    });

};

watch(tableData.value, async () => {

    await nextTick();

    setSelectedCheckBox();

});



const clearCheckBox = function () {

    cart.forEach((tableItem) => {

        const targetRow = tableData.value.find((row: any) => row.entity_id === tableItem.entity_id);

        tableRef.value.toggleRowSelection(targetRow, false);

        cart.splice(cart.findIndex((item) => item.entity_id === tableItem.entity_id));

    });

};