[TOC]
>[warning] 本項目`element ui`版本為`2.4.7`
## ele-table 使用懶加載 load 并設置默認展開項(expand-row-keys)
> 問題描述:load 需要配置 tree-props,而 hasChildren 字段為 true 時才會有展開圖標,但是如果配合 expand-row-keys 則發現下一個節點無展開圖標了!!!
### 解決方案
~~~
// 1 默認展開的項的 hasChildren 配置為 false !
// 2 配置默認展開項的下一層節點
<el-table
lazy
:data="tableData"
:load="load"
row-key="id"
:tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
:expand-row-keys="expandRow"
></el-table>
<script>
export default {
data() {
return {
expandRow: [], // 默認展開的項
tableData: []
}
},
created () {
this.tableData=[1,2,3,4,5,6,7].map((item, i) => {
const id = i.toString()
this.expandRow.push(id)
return {
id,
children: [1,2,3,4,5,6,7,8,9].map((ele, i) => ({
id: id + '-' + i,
children: [],
hasChildren: true
})), // 2 配置默認展開項的下一層節點
hasChildren: false // 1 默認展開的項的 hasChildren 配置為 false !
}
})
}
}
</script>
~~~
## ele-table 如何自定義表頭
官方推薦的方案有兩種
#### 1. 設置`Scoped slot`來自定義表頭
~~~
<el-table
:data="tableData"
// ...
>
<el-table-column
<template slot="header" slot-scope="scope">
<el-input
v-model="search"
size="mini"
placeholder="輸入關鍵字搜索"/>
</template>
<template slot-scope="scope">
// ...
</template>
</el-table-column>
</el-table>
~~~
該方案在本項目中設置未生效
#### 2. 使用屬性`render-header`方法
~~~
<el-table-column
// ...
:render-header="renderHeader"
>
<template slot-scope="scope">
// ...
</template>
</el-table-column>
~~~
>[success] 和createElement(tag,{},String)類似這里第三個參數傳遞數組用于存放子元素
> 有關標簽的屬性設置放在`props`中,事件放在`on`中
~~~
export default {
// ...
methods: {
// 重新更改表頭標題
renderHeader(h) {
return [
h(
'el-dropdown',
{ props: { placement: 'bottom-start' }, on: { command: this.handleTimeSort } },
[
h('span', { class: { 'el-dropdown-link': true } }, [
h('span', { domProps: { innerHTML: '時間' } }),
h('i', { class: { 'el-icon-arrow-down': true } })
]),
h('el-dropdown-menu', { slot: 'dropdown' }, [
h('el-dropdown-item', {
class: { 'dropdown-active': this.active },
domProps: { innerHTML: '修改時間' },
props: { command: 'lastTime' }
}),
h('el-dropdown-item', {
class: { 'dropdown-active': !this.active },
domProps: { innerHTML: '注冊日期' },
props: { command: 'createTime' }
})
])
]
)
]
},
}
}
~~~
該方案成功解決, 如果你的項目能夠支持`jsx`編譯,那么這里使用`jsx`語法會更為便捷
~~~
renderHeader() {
return (
<el-dropdown
placement="bottom-start"
:command="handleTimeSort"
// ...
>
<el-dropdown-menu slot="dropdown">
<el-dropdown-item
command="lastTime"
// ...
>
修改日期
</el-dropdown-item>
<el-dropdown-item
command="createTime"
// ...
>
注冊日期
</el-dropdown-item>
</el-dropdown-menu>
</el-dropdown>
)
}
~~~