ant design vue 表格table 默認(rèn)勾選幾項(xiàng)的操作
為什么我同樣的功能要用react 、vue 都寫一遍 ?
啊我真是不是閑的蛋疼啊(~ o ~)~zZ
在 ant design vue 中,表格的第一列是聯(lián)動的選擇框
截一張官方文檔圖,圖示最后一排就是禁用狀態(tài)
點(diǎn)擊 checkbox 會觸發(fā)onChange , 從而得到selectedRowKeys,selectedRowKeys就是選中的 key 數(shù)組。
onChange: (selectedRowKeys, selectedRows) => { console.log(`selectedRowKeys: ${selectedRowKeys}`, ’selectedRows: ’, selectedRows); },
默認(rèn)禁用disable 某項(xiàng)時,官方文檔給出了例子:
rowSelection() { const { selectedRowKeys } = this; return { onChange: (selectedRowKeys, selectedRows) => { console.log(`selectedRowKeys: ${selectedRowKeys}`, ’selectedRows: ’, selectedRows); }, getCheckboxProps: record => ({ props: { disabled: record.name === ’Disabled User’, // Column configuration not to be checked name: record.name, } }), } }
主要是getCheckboxProps 里面的disabled 屬性控制的。
默認(rèn)選中某項(xiàng)時,需要 getCheckboxProps 里面的defaultChecked 屬性控制:
業(yè)務(wù)場景:勾選了幾項(xiàng)保存之后,下次進(jìn)來編輯還是需要展示之前勾選的項(xiàng),這時候就用到了默認(rèn)勾選的屬性
之前只貼了核心邏輯,好多人好像沒看懂,我把整體的都貼上來了。
核心代碼defaultChecked: selectedRowKeys.includes(record.id) 的思路就是所有表格里所有包含已選中項(xiàng)的id,都給他默認(rèn)選中
data () { return { // ... record: ’’, rowSelection: { selectedRowKeys: [], onChange: this.onSelectChange } }, methods: { handleEdit (record) { //...省略我的業(yè)務(wù)邏輯 if (record) { //...省略我的業(yè)務(wù)邏輯 let selectedRowKeys = (record.roleIdList.length > 0 && record.roleIdList.split(’,’)) || []; this.rowSelection = { selectedRowKeys: selectedRowKeys, onChange: this.onSelectChange, getCheckboxProps: record => { return { props: {defaultChecked: selectedRowKeys.includes(record.id) } }; } }; } else { this.record = ’’; this.rowSelection = { selectedRowKeys: [], onChange: this.onSelectChange } } }, onSelectChange (selectedRowKeys) { // 去重 Array.from(new Set(arr)) this.rowSelection.selectedRowKeys = Array.from(new Set(selectedRowKeys)); } }
ant design vue 版本和 react 版本寫法略有不同,disabled 和 defaultChecked 都掛在了props 屬性下。
補(bǔ)充知識:Ant-Design-Pro中Table組件rowSelection方法的一些坑
如下所示:
<Table rowSelection={rowSelection} columns={columns} dataSource={data} />
在 <Table/> 組件中有 rowSelection={rowSelection} 方法,可以讓Table的第一列成為聯(lián)動的選擇框。
API中說到通過 rowSelection.selectedRowKeys 來控制選中項(xiàng)。比較坑的是,selectedRowKeys 控制的只是dataSource當(dāng)前的順序編號。
一定要加上rowKey='id'或者rowKey={record => record.id},后來經(jīng)過多次調(diào)試發(fā)現(xiàn)很多BUG都跟這個參數(shù)有關(guān),不然會導(dǎo)致聯(lián)動的選擇框狀態(tài)異常。id可以自定義為dataSource中的某個值。
以上這篇ant design vue 表格table 默認(rèn)勾選幾項(xiàng)的操作就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
