(一)table 组件中实现单选功能
通过 iview 官网可以看到,官方已经实现了 table 组件单选功能,那我们来看看如何使用吧
1.通过设置属性 highlight-row
,可以选中某一行。
<i-table highlight-row :columns="columns3" :data="data1"></i-table>
2.当选择时,触发事件 @on-current-change
,可以自定义操作,事件返回两个值 currentRow
和 oldCurrentRow
,分别为当前行的数据和上一次选择的数据。
<i-table highlight-row :columns="columns3" :data="data1" @on-current-change="changeRow"></i-table>
changeRow(currentRow, oldCurrentRow) {
console.log(currentRow, oldCurrentRow)
}
3.通过给 columns
数据设置一项,指定 type: 'index'
,可以自动显示一个从 1 开始的索引列。使用 indexMethod
可以自定义序号。
columns3: [{
type: 'index',
width: 60,
align: 'center',
indexMethod: (row) => {
return row._index * 2
}
}],
4.给 data 项设置特殊 key _highlight: true
可以默认选中当前项。
data1: [{
name: 'John Brown',
age: 18,
address: 'New York No. 1 Lake Park',
date: '2016-10-03',
_highlight: true
}]
5.调用 clearCurrentRow
方法可以手动清除选中项。
<i-table
highlight-row
ref="currentRowTable"
:columns="columns3"
:data="data1"
@on-current-change="changeRow"
></i-table>
<i-button @click="handleClearCurrentRow">Clear</i-button>
clearCurrentRow: 清除高亮项,仅在开启 highlight-row
时可用
handleClearCurrentRow () {
this.$refs.currentRowTable.clearCurrentRow();
},
详细案例,参考 iview 官网 table 组件 单选案例
(二)table 组件中实现自定义单选样式功能
<i-table
border
:row-class-name="rowClassName1"
:columns="columns1"
:data="data1"
@on-row-click="rowClick1"
></i-table>
1.对于选择样式的修改:
row-class-name | 行的 className 的回调方法,传入参数:
| Function | - |
rowClassName1(row, index){
if (this.currentSelection1 === index){
return 'selected'; // 选择样式 class
} else {
return '';
}
},
2.点击单行事件:
on-row-click | 单击某一行时触发 |
|
rowClick1(data, index){
if (this.currentSelection1 === index){
this.currentSelection1 = ''; //双击取消
}else {
this.currentSelection1 = index; // 单击切换
}
},
扩展:
(1)table 组件如何指定行列样式呢?row-class-name
(2)那 table 组件,如何根据某一个列中的状态变换不同的字体颜色?
columns3: [{
title: '业主项目部',
key: 'yzxmb',
align: "center",
tooltip: true,
render: function(h, params) {
return h('span', {
style: {
color: '#00FFFF'
}
})
}
}],