el-table set selection multi-choice to achieve single-choice function

The requirement is to use the multi-selection function of el-table, and then do not want to change the multi-selection to single-selection.
insert image description here
the code

<template>
  <div class="contentBox"
       v-loading="loading">
 <el-table :data="list"
                ref="accountRef"
                @select="handleTableChange">
        <el-table-column type="selection"  width="45"></el-table-column>
        <el-table-column width="100" prop="name"></el-table-column>
        <el-table-column width="100" prop="no"></el-table-column>
        <el-table-column width="100" prop="date"></el-table-column>
   </el-table>     
   </div>
   </template>                 
<script>
import {
    
    
  defineAsyncComponent,
  defineComponent,
  getCurrentInstance,
  onMounted,
  reactive,
  toRefs,
} from "vue";

export default defineComponent({
    
    
  components: {
    
     },
  setup(props, context) {
    
    
    const {
    
     proxy } = getCurrentInstance();
    const accountRef = ref(null)
    const data = reactive({
    
    
      list: [],
      selectTable: [],
    });
    //表格单选
    const handleTableChange = (list, row) => {
    
    
      if (list.length === 0) {
    
    
        data.selectTable = [];
        return
      }
      // let itemData = JSON.parse(JSON.stringify(row))
      accountRef.value.clearSelection()
      data.list.forEach((ele) => {
    
    
        if (ele.id === row.id) {
    
    
          accountRef.value.toggleRowSelection(ele, true)
          data.selectTable = [ele];
        }
      })
    };
    return {
    
    
      ...toRefs(data),
      handleTableChange,
      accountRef
    };
  },
});
</script>

Here is the way of writing vue3
1. Bind the table instance ref="accountRef", and then write down the statement const accountRef = ref(null) and add accountRef in the return return.
2. Bind the select method and define the handleTableChange function @select="handleTableChange"
3. The table binding event select, select has two fallback parameters selection, row. The data array selected by selection, the data currently selected by row.
4. The table method, clearSelection() clears the table selection, toggleRowSelection(ele, true) manually selects. First clear the selection, and then check the piece of data you choose.
5. toggleRowSelection has two parameters, one is the data to be selected, the other is the state of the data, true is selected, false is not selected

Guess you like

Origin blog.csdn.net/m0_49016709/article/details/126855032