element ui是一個很是不錯的vue的UI框架,element對table進行了封裝,簡化了vue對錶格的渲染。
element ui表格中有一個功能是展開行,在2.0版本官網例子中,只能夠點擊右箭頭能夠展開,咱們的不少需求是點擊某一行展開
那是否是沒法實現呢?其實,藉助element ui的一些屬性,輕鬆實現點擊某行展開,咱們仍是用2.0.9版本官網的例子,
對齊改造,使之能夠作到這點
<template>
<el-table
:data="tableData5"
style="width: 100%"
row-key="id"
:expand-row-keys="expands"
@row-click="rowClick">
<el-table-column type="expand">
<template slot-scope="props">
<el-form label-position="left" inline class="demo-table-expand">
<el-form-item label="商品名稱">
<span>{{ props.row.name }}</span>
</el-form-item>
<el-form-item label="所屬店鋪">
<span>{{ props.row.shop }}</span>
</el-form-item>
<el-form-item label="商品 ID">
<span>{{ props.row.id }}</span>
</el-form-item>
<el-form-item label="店鋪 ID">
<span>{{ props.row.shopId }}</span>
</el-form-item>
<el-form-item label="商品分類">
<span>{{ props.row.category }}</span>
</el-form-item>
<el-form-item label="店鋪地址">
<span>{{ props.row.address }}</span>
</el-form-item>
<el-form-item label="商品描述">
<span>{{ props.row.desc }}</span>
</el-form-item>
</el-form>
</template>
</el-table-column>
<el-table-column
label="商品 ID"
prop="id">
</el-table-column>
<el-table-column
label="商品名稱"
prop="name">
</el-table-column>
<el-table-column
label="描述"
prop="desc">
</el-table-column>
</el-table>
</template>
<style>
.demo-table-expand {
font-size: 0;
}
.demo-table-expand label {
width: 90px;
color: #99a9bf;
}
.demo-table-expand .el-form-item {
margin-right: 0;
margin-bottom: 0;
width: 50%;
}
</style>
<script>
export default {
data() {
return {
tableData5: [{
id: '12987122',
name: '好滋好味雞蛋仔',
category: '江浙小吃、小吃零食',
desc: '荷蘭優質淡奶,奶香濃而不膩',
address: '上海市普陀區真北路',
shop: '王小虎夫妻店',
shopId: '10333'
}, {
id: '12987123',
name: '好滋好味雞蛋仔',
category: '江浙小吃、小吃零食',
desc: '荷蘭優質淡奶,奶香濃而不膩',
address: '上海市普陀區真北路',
shop: '王小虎夫妻店',
shopId: '10333'
}, {
id: '12987125',
name: '好滋好味雞蛋仔',
category: '江浙小吃、小吃零食',
desc: '荷蘭優質淡奶,奶香濃而不膩',
address: '上海市普陀區真北路',
shop: '王小虎夫妻店',
shopId: '10333'
}, {
id: '12987126',
name: '好滋好味雞蛋仔',
category: '江浙小吃、小吃零食',
desc: '荷蘭優質淡奶,奶香濃而不膩',
address: '上海市普陀區真北路',
shop: '王小虎夫妻店',
shopId: '10333'
}],
// 要展開的行,數值的元素是row的key值
expands: []
}
},
methods:{
//在<table>裏,咱們已經設置row的key值設置爲每行數據id:row-key="id"
rowClick(row, event, column) {
Array.prototype.remove = function (val) {
let index = this.indexOf(val);
if (index > -1) {
this.splice(index, 1);
}
};
if (this.expands.indexOf(row.id) < 0) {
this.expands.push(row.id);
} else {
this.expands.remove(row.id);
}
}
}
}
</script>
這個例子能夠直接複製運行起來,一點問題都沒有,上面的代碼能夠實現點擊某行展開,對比官網的例子,咱們在table添加了
row-key="id" :expand-row-keys="expands" @row-click="rowClick"
這裏有2個問題:
1.數據中每項沒有一個惟一標示怎麼辦?
2.實現展開當前行的時候,其餘行都能收起來
這2個問題也很簡單。第2個問題,在rowClick函數給expands添加以前,先清空這個數組。
if (this.expands.indexOf(row.id) < 0) {
this.expands = []
this.expands.push(row.id);
} else {
this.expands.remove(row.id);
}