效果:不只是帶單選框,點擊當前行單選框選中狀態
網上查了一些發現很多都是只能點擊當前radio選中當前行,配合element-ui的單選table時發現兩個的選擇狀態是不一致的,所以調整了一下
效果
提供下思路:
1.保證不止是點擊單選框,點擊列表某行也能夠選中,通過設置highlight-current-row和@current-change="handleCurrentChange"實現
2.radio為單選框的值,選中后為當前行數,翻頁后為保證重新選中狀態需要重制
3.我的項目里需求是組件化形式,單選框選中值傳遞給父組件,父組件可能會有默認數據傳入,需要在打開時設置點選狀態
部門關鍵代碼
<template>
<el-table
:data="tableData"
ref="orderTable"
@current-change="handleCurrentChange"
tooltip-effect="light"
highlight-current-row
:cell-style="cellStyle"
>
<!--
為空,不加這個radio的label會顯示index數字,注意從0開始的;radio會全選的問題是label相同導致的
disabled設置單選框是否可以被選擇
-->
<el-table-column label="選擇" width="50" center>
<template slot-scope="scope">
<el-radio
class="radio"
v-model="radio"
:label="scope.$index"
@change.native="getCurrentRow(scope.$index)"
:disabled="scope.row.Enable==1?false:true">
</el-radio>
</template>
</el-table-column>
</el-table>
<el-pagination
background
layout="total, prev, pager, next"
:current-page.sync="pagination.pageNum"
:page-size="pagination.pageSize"
:total="pagination.total"
@current-change="changePage"
:pager-count="5"
></el-pagination>
</template>
<script>
export default {
data() {
return {
currentRow: null,
radio: false,
tableData: [],
},
porps:{
//父組件傳遞過來的初始選中值,根據自己項目需求設置
chooseData:{
type:Object
}
},
watch:{
//觀察是否有父組件傳遞的初始值或者變化,重新選中
chooseData(val){
if(val){
this.radio = false
this.getInitChoose()
}
}
},
methods:{
getList() {
this.isListLoading = true;
getTableData().then(res => {
this.tableData = res.item;
//每次數據改變重新判斷單選狀態
this.getInitChoose();
})
},
//設置單選框選擇狀態
getInitChoose() {
if (this.chooseData) {
let index = this.tableData.findIndex(
item => item.userUuid == this.chooseData.id
);
if (index > -1) {
this.radio = index;
}
},
//由於翻頁后重新獲取列表了,需要把選擇框選中狀態取消
changePage(pageNum) {
this.pagination.pageNum = pageNum;
this.radio = false
this.getList()
},
/* current-change 當表格的當前行發生變化的時候會觸發該事件,如果要高亮當前行,請打開表格的 highlight-current-row 屬性 currentRow, oldCurrentRow */
//保證點擊當前行的任意位置不止是單選框也能夠選擇
handleCurrentChange(val) {
if (val && val.Enable == 1) {
this.currentRow = val;
let index = this.tableData.findIndex(
item => item.userUuid == this.currentRow.userUuid
)
if (index > -1) {
this.radio = index;
}
this.$emit('data',val.pkg)
},
getCurrentRow(index) {
this.radio = index
},
}
}
</script>