【study】表格删除/增加/上移/下移一行数据

45 阅读1分钟
  1. findIndex删除
const onDelete = (value) => {
       const { skuId } = value;
       const deleteIndex = props.formData.skuInfoList.findIndex(item => item.skuId === skuId);
      props.formData.skuInfoList.splice(deleteIndex, 1);
};
  1. vue3 hooks 封装删除
import {
    getCurrentInstance,
} from '@vue/composition-api';

export function useDelete() {
    const { proxy } = getCurrentInstance();
    // 删除
    const handleDeleteItem = (list, index, name) => {
        proxy.confirm({
            title: '确认删除',
            message: `你确定要删除${name}-${index + 1}吗?`,
            width: '430px',
            showCancelButton: true,
            type: 'warning',
            okButtonText: '删除',
            okButtonProps: {
                type: 'danger',
            },
        }).then(() => {
            if (list.length > 1) {
                list.splice(index, 1);
            } else {
                proxy.message.error('最少要有一组');
            }
        }).catch(() => {});
    };

    return {
        handleDeleteItem,
    };
}
  1. vue3 hooks 封装增加
export function useAdd(uniqueIdentifier) {
    const handleAddItem = (list, additionalProperties = {}) => {
        const newItem = {
            data: '',
            value: {
                type: '',
                url: '',
            },
            uniqueId: uniqueIdentifier.value,
            ...additionalProperties,
        };
        list.push(newItem);
        // eslint-disable-next-line no-plusplus
        uniqueIdentifier.value++;
    };

    return {
        handleAddItem,
    };
}

  1. 上移
function moveItemUp(list, index) {
    if (index > 0) {
        // 提取要移动的项
        const itemToMoveUp = list[index];
        // 删除点击的位置那一项
        list.splice(index, 1);
        // 插入到新的位置
        list.splice(index - 1, 0, itemToMoveUp);
    }
}
  1. 下移
function moveItemDown(list, index) {
    if (index < list.length - 1) {
        const itemToMoveDown = list[index];
        list.splice(index, 1);
        list.splice(index + 1, 0, itemToMoveDown);
    }
}