vue3+ts+element-plus的表格的默认勾选复选框以后,刷新页面,会调用selection-change事件?

![image.png](/img/bVc6L这个是写的html

// 获取每一行的key
const rowKey = (row:any) => {
  return row.id;
};
// 勾选复选框事件
const handleSelectionChange = (selection: User) => {
  let currentRow;
    if (selection.length > multipleSelection.value.length) {
      // 勾选了复选框
      currentRow = selection.slice(-1)[0]; // 获取最后一个元素
    } else {
      // 取消了复选框
      currentRow = multipleSelection.value.find(
        (row:any) => !selection.includes(row)
      ); // 获取不在 selection 中的元素
    }
    multipleSelection.value = selection
    SelectionChange(currentRow)
}
const SelectionChange = (row:any) => {
    SigCategoryUpdate({
      id: row?.id,
      category: row?.category,
      enable: !row?.enable
    }).then(res => {
      if(res.code === 200) {
        tableData.value.forEach((item:any) => {
          if(item.id === row.id){
            item.enable = !row.enable
          }
        })
        nextTick(() => toggleSelection(tableData.value))
      }
    })
}

这个是进入页面的时候获取到数据,添加默认的勾选框

const getRuleManageData = () => {
  RuleManage({
    engine: 'engine-1'
  }).then(res => {
    if(res.code === 200) {
      listLoading.value = false
      tableData.value = res.data.sig_category
      nextTick(() => toggleSelection(res.data.sig_category))
    }
  })
}
const toggleSelection = (rows: any) => {
  if(rows) {
    rows.forEach((row: any) => {
      if(row.enable) {
        multipleTableRef.value!.toggleRowSelection(row,row.enable)
      }
    })
  }else {
    multipleTableRef.value!.clearSelection()
  }
}

我在改变了勾选框状态以后,刷新页面他会自动执行handleSelectionChange事件里面的SelectionChange事件,导致选中的也会变为没选中,如何解决有没有什么方法,麻烦给我指正一下

阅读 2.5k
1 个回答

你先修改 toggleSelection:

const toggleSelection = (rows: any, isInitialLoad: boolean) => {
  if(rows) {
    rows.forEach((row: any) => {
      if(row.enable) {
        multipleTableRef.value!.toggleRowSelection(row, row.enable, isInitialLoad);
      }
    })
  }else {
    multipleTableRef.value!.clearSelection()
  }
}

然后,在 getRuleManageData 中调用 toggleSelection 时候,传true 作为 isInitialLoad 参数:

const getRuleManageData = () => {
  RuleManage({
    engine: 'engine-1'
  }).then(res => {
    if(res.code === 200) {
      listLoading.value = false
      tableData.value = res.data.sig_category
      nextTick(() => toggleSelection(res.data.sig_category, true))
    }
  })
}
推荐问题
logo
Microsoft
子站问答
访问
宣传栏