官方文档给的例子太简单了,如果初始就要选中某些选项或者要自定义样式比较困难,网上也没找到比较靠谱的方法。

1 首先自定义表头

这个官方说的很详细,简单列出一下

<el-table>
  <el-table-column
    size="small"
    type="selection"
    align="center">
  </el-table-column>
</el-table>

将type设为selection即可

2 接着自定义每列的复选框

其实上面代码已经可以实现每一列都有复选框,并且在el-table标签添加select事件也可以实现点击每一行的事件,但是如果你的数据一开始就是选中的,或者你想自定义复选框,那么就要另想办法了

html

<el-table
  ref="tableRef"        
  :data="tableList"        
  :header-cell-style="headerStyle"        
  :cell-style="cellStyle"       
  @select-all="selectAll">        
  <el-table-column
    size="small"         
    type="selection"          
    align="center">          
    <template #default="scope">          
      <el-checkbox v-model="scope.row.checked" @change="select"/>          
     </template>         
  </el-table-column>
  ...
</el-table>          

js

import { ref, reactive, onMounted } from 'vue'
const tableRef = ref() // 定义ref
const tableList = ref([ // 表格数据
  {
    checked: true,
    ...
  },
  {
    checked: false,
    ...
  },
  ...
])
const headerStyle = reactive({ background: '#FAFAFA', color: '#666' }) // table样式
const cellStyle = reactive({ height: '45px' }) // 单元格样式
onMounted(() => {
  select()
})
const selectAll = row => { // 全选
  tableList.value.forEach(t => {
    t.checked = !!row[0]
  })
}
const select = () => { // 反选
  tableList.value.forEach(t => {
    multipleTableRef.value.toggleRowSelection(t, t.checked)
  })
}

这样就可以实现自定义复选框已经全选反选功能了,至于自定义样式只要在el-table-column的插槽中添加想要的图标将原本的复选框遮住,然后将事件绑定给图标即可

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐